开发者

PHP anonymous function declaration in an existing class object [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Initialize class property with an anonymous function

I've been programing PHP for quite a while, and PHP 5.3 anonymous functions are one of those thinks that help you out a lot while building some simple scripts. However, I cannot understand why would the following example won't work?

$db         = new PDO([..]);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
$db->die    = function($str){ die(var_dump( $str )); };

$db->die('[..]');

After all, all I do is declare anonymous function on ->die property of PDO instance. This kinda 开发者_高级运维makes me think this is a PHP bug.


Assigning a function to a property does not change the property into a function. To execute a function stored within a property you must use the __call Magic Method:

class Foo extends PDO {
    function __call($function, $args) {
        return call_user_func_array($this->{$function}, $args);
    }
}

$db         = new Foo([..]);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
$db->die    = function($str){ die(var_dump( $str )); };

$db->die('[..]');


According to the answers to this question: php Set a anonymous function in an instance

It is by design (or a design error). There are some workaround suggestions provided there.


This works:

class Foo{
    public $bar;
}
$foo = new Foo;
$foo->bar = function(){
    echo "Hello, world\n";
};
call_user_func($foo->bar);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜