我试图通过可调用对象调用类的构造函数,因此我有以下代码:
$callable = array('Foo', '__construct');
Run Code Online (Sandbox Code Playgroud)
但是调用此方法会引发以下错误:
Fatal error: Non-static method Foo::__construct() cannot be called statically
Run Code Online (Sandbox Code Playgroud)
我知道构造函数不是静态方法,但我不能使用现有实例来调用新实例的构造函数(因为它只会再次调用现有对象上的构造函数),有什么方法可以像这样调用构造函数?
如果您正在寻找一种简单的方法来动态选择要构造的类,您可以使用带有new关键字的变量名称,如下所示:
$inst = new $class_name;
// or, if the constructor takes arguments, provide those in the normal way:
$inst = new $class_name('foo', 'bar');
Run Code Online (Sandbox Code Playgroud)
但是,如果您需要一种将构造函数传递给已经需要可调用的东西的方法,我能想到的最好的方法是将其包装在匿名函数中:
$callable = function() { return new Foo; }
call_user_func( $callable );
Run Code Online (Sandbox Code Playgroud)
或者使用 PHP 7.4 中引入的短单表达式闭包语法:
$callable = fn() => new Foo;
call_user_func( $callable );
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2567 次 |
| 最近记录: |