Re: [PHP] new $foo->className(); Class name must be a valid object or a string

[email protected] (Casey)
Newsgroups php.general
Message-ID <[email protected]>
On May 3, 2008, at 4:46 PM, Jack Bates <[email protected]> wrote:

> I am trying to load PHP objects stored in a database, where the class
> name is stored in a column:
>
> $object = new $resultSet->getString(1);
>
> This fails for the same reason that the following fails:
>
> <?php
>
> class Foo
> {
>  public function className()
>  {
>    return 'Foo';
>  }
> }
>
> $foo = new Foo;
> $bar = new $foo->className();
>
> Fatal error: Class name must be a valid object or a string in test.php
> on line 12
>
> I guess this error is due to the confusion of parsing "()" as the
> argument list for the "className" function, or the "Foo"  
> constructor...
>
> I work around this error by using a temp variable:
>
> $tmp = $foo->className(); $bar = new $tmp;
>
> - however the above reads like hacky code : (
>
> When calling dynamically named functions, I generally use
> call_user_func() to avoid awkwardness with $object->$tmp($arg1, ...)
>
> In other words, I prefer:
>
> call_user_func(array($object, 'get'.$someName), $arg1, ...);
>
> - to:
>
> $tmp = 'get'.$someName; $object->$tmp($arg1, ...);
>
> However there does not appear to be an analog of call_user_func() for
> constructing new instances of dynamically named classes?
>
> If I recall correctly, there was also a way to work around calling
> dynamically named functions (e.g. $object->$tmp($arg1, ...);) using
> curly braces:
>
> $object->{'get'.$someName}($arg1, ...);
>
> - however I cannot recall the exact syntax.
>
> Can anyone confirm that there is a curly brace syntax for calling
> dynamically named functions? Could it be applied to instantiating
> dynamically named classes?
>
> Can anyone recommend a cleaner alternative to:
>
> $tmp = $foo->className(); $bar = new $tmp;
>
> Thanks and best wishes, Jack
>
Does...
<?php
  $bar = new $foo->className()();
?>
...work?

Otherwise, I'd just do...
<?php
  $className = $foo->className();
  $bar = new $className;
?>
...instead of $tmp.
>
> -- 
> PHP General Mailing List (http://www.php.net/)
> To unsubscribe, visit: http://www.php.net/unsub.php
>
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.