php - 通过工厂用字符串实例化 PHP 对象

标签 php reflection propel

这类似于 Can PHP instantiate an object from the name of the class as a string? .

我在 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+ 的问题

最佳答案

使用 PHP5.3 完全按照您描述的方式(据我所知)工作。不过如果还是用5.2的话,可以用反射

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

或者只是

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

值得一提的是,这是“非常神奇的”,当你有很多这样的结构时,会很难理解会发生什么。

关于php - 通过工厂用字符串实例化 PHP 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9023881/

相关文章:

php - 如何使用 Propel ORM 查找数据库中的重复条目?

php - Symfony 1.4 插入 : Accessing Table Data via Foreign Key

php - 用php函数替换模板中的占位符

php - 如何将图像添加到此文本?

java - 使用循环设置 Bean 的属性

c# - 确定最接近类的子接口(interface)

php - 从购物车内容获取帖子 ID

php - 如何在 Windows 10 上将 Xdebug 3 连接到 PhpStorm?

java - 从类型获取自动框类

database - Zend 与现有的 Propel ORM