通过工厂用字符串实例化 PHP 对象
这类似于 PHP 可以通过类名将对象实例化为字符串吗?。
我在 PHP 5.2.17 中使用 propel orm,我想将查询类的名称存储在数据库中,例如“AuthorQuery”,然后使用它来获取查询对象。使用 propel 可能有不同的方法来做到这一点,避免使用 ::create()
工厂方法。该解决方案将受到欢迎,但我更想知道这是否可以用 php 实现(如果答案是“不可能”,我不会感到非常惊讶)。
问题就在这里。这将起作用:
$author_class = "Author";
$author = new $author_class();
使用 new
关键字,字符串将被解释为类名。
但是当我尝试使用工厂构造函数来执行此操作时,我收到 语法错误,意外的 T_PAAMAYIM_NEKUDOTAYIM
(指的是 ::
):
$author_query_class = "AuthorQuery";
$author_query = $author_query_class::create(); // syntax error at the ::
我需要额外的 $
还是什么?
事实证明,这对于 PHP 5.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+
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
与 PHP5.3 所描述的完全一样(据我记得)。但是,如果您仍然使用 5.2,则可以使用反射
,或者
值得一提的是,这是“非常神奇”,当您有许多这样的构造时,会很难理解会发生什么。
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
Or just
Worth to mention, that this is "much magic" and it will get hard to understand, what happens, when you have many of such constructions.
这与这一行有关:
这是因为(引自《PHP Master》一书):
您可以在 PHP 5.3 中执行类似的操作,并且 PHP 5.4 也将提供更多支持。在 PHP 5.2 之前,您可能必须使用类似提供的其他答案或 gulp、
eval()
的内容。This has to do with this line:
It is because (as quoted from the book PHP Master):
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()
.