are there ways to pass a "method reference" to a function that accept a callback?
Eg.:
function ex($callback){
$callback();
}
$obj = (object) ['f' => function(){echo "hello";}];
ex($obj->a)
Obviously this is a very simplistic case, image having a complex object $obj
with parameters inside
CodePudding user response:
PHP does not work like Javascript.
This code:
$obj = (object) ['f' => function(){echo "hello";}];
Does not define "an object with method f()
" it defines "an object with property f
that happens to be a callable type".
Calling $obj->f();
directly results in:
Fatal error: Uncaught Error: Call to undefined method stdClass::f()
It would need to be specially handled like:
$func = $obj->f;
$func();
Or:
($obj->f)();
While not a wholly accurate statement, you could consider it that callable types need the equivalent of "being dereferenced" before they can actually be called.
You example is something of a "successful error" in that it attempts to use "first class functions" which PHP does not have, but on a malformed object that allows this to not fail.
Using a proper class:
function ex($callback){
$callback();
}
class Example {
public function f_instance() {
echo "instance call\n";
}
public static function f_static() {
echo "static call\n";
}
}
ex(['Example', 'f_static']);
$e = new Example();
ex([$e, 'f_instance']);
Output:
static call
instance call
Ref: https://www.php.net/manual/en/language.types.callable.php