Is it possible to add methods to functions?
For example:
<?
function func(){
;
}
//add method
func->test = function(){
;
}
func->test();
func();
I’m coming from a javascript background, and therefore I’m used to ‘everything is an object’.
EDIT:
I was just explaining where the misconception may often come from for new phpers. I understand the above code doesn’t work.
EDIT 2
Figured it out.
class myfunc_class{
function __invoke(){
//function body
}
function __call($closure, $args)
{
call_user_func_array($this->$closure, $args);
}
}
$func = new myfunc_class;
$func->test = function(){
echo '<br>test<br>';
};
$func->test();
$func();
Even sexier 🙂
class func{
public $_function;
function __invoke(){
return call_user_func_array($this->_function,func_get_args());
}
function __construct($fun){
$this->_function = $fun;
}
function __call($closure, $args)
{
call_user_func_array($this->$closure, $args);
}
}
$func = new func(function($value){
echo $value;
});
$func->method = function(){
echo '<br>test<br>';
};
$func('someValue');
$func->method();
No, because an object is a different PHP language construct than a function. Functions do not have properties, but are instead simply execution instructions.
But, if
funcwere instead a pre-defined class, then yes… with a bit of witchcraft, ignoring public outcry, foregoing readability and PHP coding standards, and by using closures with the__call()magic method…This won’t work as you’d think without
__call(), because by$obj->test(1,1), PHP thinks you’re trying to call a non-existent method offuncwhen out of object scope. But inside, being that the new"test"property is of a type: closure, thecall_user_func_array()just sees the"test"property as just another function, so you can hide this bit of trickery from outside scope.