3

This is similar to Can PHP instantiate an object from the name of the class as a string?.

I'm using propel orm with PHP 5.2.17, and I want to store the name of a query class in the database, say "AuthorQuery", then use it to get a query object. There may be a different way to do this with propel, avoding the ::create() factory method. That solution would be welcome, but I'd rather to know if this is even possible with php (I won't be terribly surprised if the answer is "It's not").

Here's the problem. This will work:

$author_class = "Author";
$author = new $author_class();

Using the new keyword a string will get interpreted as the class name.

But I get syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM (that's referring to the ::) when I try to do it using a factory constructor instead:

$author_query_class = "AuthorQuery";
$author_query = $author_query_class::create();  // syntax error at the ::

Do I need an extra $ or something?

It turns out, this is not an issue for PHP 5.3+

Community
  • 1
  • 1
Joe Flynn
  • 6,908
  • 6
  • 31
  • 44

3 Answers3

3

Works exactly the way you describe (as far as I remember) with PHP5.3. However, if you still use 5.2, you can use reflection

$x = new ReflectionClass($author_query_class);
$author_query = $x->getMethod('create')->invoke(null);

Or just

$author_query = call_user_func(array($author_query_class, 'create'));

Worth to mention, that this is "much magic" and it will get hard to understand, what happens, when you have many of such constructions.

KingCrunch
  • 128,817
  • 21
  • 151
  • 173
1
$author_query=call_user_func("$author_query_class::create");
Eugen Rieck
  • 64,175
  • 10
  • 70
  • 92
0

This has to do with this line:

$author_query_class::create();

It is because (as quoted from the book PHP Master):

The double colon operator that we use for accessing static properties or methods in PHP is technically called the scope resolution operator. If there’s a problem with some code containing ::, you will often see an error message containing T_PAAMAYIM_NEKUDOTAYIM. This simply refers to the ::, although it looks quite alarming at first! “Paamayim Nekudotayim” means “two dots, twice” in Hebrew.

You can do something like this in PHP 5.3 and more support is is on the table for PHP 5.4. Before PHP 5.2 you may have to use something like the other answers provided or , gulp, eval().

Jason McCreary
  • 71,546
  • 23
  • 135
  • 174