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
As of PHP5.3, you can also create Lambdas with
$lambda = function() { return TRUE; };
See the PHP manual on Anonymous functions for further reference.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…