5

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?

php_nub_qq
  • 15,199
  • 21
  • 74
  • 144

2 Answers2

5

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

Tofandel
  • 3,006
  • 1
  • 29
  • 48
2

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);
monocell
  • 1,411
  • 10
  • 14
  • Thank you for the answer, but can you tell me also why this is not working? I mean if I were to use an array instead of an object then I'd be able to call the function with `$x['cast'](5)`but with an object it's not working? – php_nub_qq Apr 16 '14 at 22:07
  • I don't know enough about php internals to give a really confident answer, but I believe it's just a matter of php not looking for properties that might be functions when you call a method on an object. Normally when you have a construction that looks like a function call php will try to interpret it as such in several different ways, proper function, string, array, etc, but I guess it's different with objects. – monocell Apr 16 '14 at 22:13