在PHP中动态创建实例方法
我想能够在类的构造函数中动态创建一个实例方法,如下所示:
I'd like to be able to dynamically create an instance method within a class' constructor like so:
class Foo{
function __construct() {
$code = 'print hi;';
$sayHi = create_function( '', $code);
print "$sayHi"; //prints lambda_2
print $sayHi(); // prints 'hi'
$this->sayHi = $sayHi;
}
}
$f = new Foo;
$f->sayHi(); //Fatal error: Call to undefined method Foo::sayHi() in /export/home/web/private/htdocs/staff/cohenaa/dev-drupal-2/sites/all/modules/devel/devel.module(1086) : eval()'d code on line 12
问题似乎是lambda_2函数对象在构造函数中没有绑定$ this。
The problem seems to be that the lambda_2 function object is not getting bound to $this within the constructor.
任何帮助都将被欣赏。
您将匿名函数分配给属性,但是尝试使用属性名称调用方法。 PHP不能自动从属性中取消引用匿名函数。以下将工作
You are assigning the anonymous function to a property, but then try to call a method with the property name. PHP cannot automatically dereference the anonymous function from the property. The following will work
class Foo{
function __construct() {
$this->sayHi = create_function( '', 'print "hi";');
}
}
$foo = new Foo;
$fn = $foo->sayHi;
$fn(); // hi
您可以利用魔术 __调用
方法来截取无效的方法调用,以查看是否有一个持有回调/匿名函数的属性:
You can utilize the magic __call
method to intercept invalid method calls to see if there is a property holding a callback/anonymous function though:
class Foo{
public function __construct()
{
$this->sayHi = create_function( '', 'print "hi";');
}
public function __call($method, $args)
{
if(property_exists($this, $method)) {
if(is_callable($this->$method)) {
return call_user_func_array($this->$method, $args);
}
}
}
}
$foo = new Foo;
$foo->sayHi(); // hi
从PHP5.3开始,您还可以使用
As of PHP5.3, you can also create Lambdas with
$lambda = function() { return TRUE; };
请参阅匿名功能的PHP手册供进一步参考。