ok I do have the code below
<?php
class foo{
public $bar = NULL;
public function boo(){
$this->bar();
}
}
$mee = new foo();
//save a closure function on the property
$mee->bar = function(){
echo 'hahaha';
};
//invoke the closure function by using a class method
$mee->boo();
?>
and you can see it running here http://codepad.org/s1jhi7cv
now what i want here is to store the closure function on the class method.
well closures are possible as i read the documentation about it here http://php.net/manual/en/functions.anonymous.php
is this possible? did i went to something wrong? please correct me
You need to exploit some magic functionality of PHP (
__call
) to make use of that. Extend fromExtendable
for example:And you can do the job. It's not that nice. Background and examples are in one of my blog posts:
You can naturally implement that magic functionality your own, too.
PHP is not a prototype based language hence you cannot redefine functions
Your example code at codepad.org does not work because codepad.org uses PHP 5.2.5, and closure support was only added in 5.3.
However, your code will also not work in a PHP version that supports closures, although you will get a different error: http://codepad.viper-7.com/Ob0bH5
This is a limitation of PHP at present.
$obj->member()
looks for a method namedmember
and will not look at properties to see if they are callable. It is, frankly, annoying.The only way I am aware of to make this work without
call_user_func()
/call_user_func_array()
is:Use
__call
to catch all non-defined methods and then look up the closure and invoke it. Take a look at my post on this SitePoint thread.You will not be able to do that.
Take for example this code:
It works fine on PHP 5.4.6 and/or PHP 5.3.16, however it will result in
T::foo
getting printed.This happens because methods, in PHP, are not modifiable class properties, as they are for example in javascript.
However,
will print
Closure::foo
as expected.Use
call_user_func()
function:This will display "ahahah"
Hope it helps.