This is what I have
$x = new \stdClass();
$x->cast = function($y){
return $y;
};
and when I try to execute it
$x->cast(5);
I get this error
Fatal error: Call to undefined method stdClass::cast()
How can I fix it?
This is what I have
$x = new \stdClass();
$x->cast = function($y){
return $y;
};
and when I try to execute it
$x->cast(5);
I get this error
Fatal error: Call to undefined method stdClass::cast()
How can I fix it?
The problem is that you're defining a variable and assigning it a closure function inside your stdClass
If you want to understand why calling $x->cast(5);
doesn't work it's because PHP is looking for a method of the class named 'cast' but there is no such method instead only a property named 'cast', properties and methods are two different things for PHP
So for what you want to achieve to work you need to call (PHP 7+ syntax only)
($x->cast)(5);
Or for PHP 5.3+
$x->cast->__invoke(5)
Or for any version
call_user_func($x->cast, 5);
to tell the compiler that first you want to access the variable (which returns the closure) and then to call this closure with the parameter 5
In general it's nicer to just make a class if you want to attach functions to objects but in case you really want this then this should work:
$x = new \stdClass();
$x->cast = function($y){
return $y;
};
$y = $x->cast;
var_dump($y(5));
or
call_user_func($x->cast, 5);