3

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.

2
  • What happens? What does new PDO([..]) stand for? Commented Jun 26, 2011 at 12:02
  • It will simply produce Fatal error: Call to undefined method PDO::die() in [..] on line [..] Commented Jun 26, 2011 at 12:03

3 Answers 3

1

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('[..]');
Sign up to request clarification or add additional context in comments.

Comments

0

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.

6 Comments

That's a different case. I declare the anonymous function after the instance is initiated. There is no obvious reason for it to fail.
@Guy ah, true. The answers in the second link should apply in any case though?
Are you referring to __call() "workaround"? That requires extending the original class and generally brakes the concept of anonymous function.
@Guy no, I mean the call_user_func_array() workaround that should work regardless of whether you extend the original class or not. It's far from elegant though. This can be viewed as a design flaw, but I don't think there is anything that can be done (except complaining to PHP developers about this, and asking that it be fixed in a future version)
Anyway, I will keep the answer alive for few more hours, to see if anyone stands in with a more reasoned explanation.
|
0

This works:

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

1 Comment

You can change call_user_func with $func = $foo->bar; $func();

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.