Strange closing behavior

I wonder why this is not working: ( PHP Fatal error: Call to undefined method stdClass::y())

$x=new stdClass;
$x->y=function(){return 'hi';};
echo $x->y();

but it works:

$x=new stdClass;
$x->y=function(){return 'hi';};
$y=$x->y;
echo $y();

echo ($x->y)();also return Parse error: syntax error, unexpected '(', expecting ',' or ';'invalid. So, what is the correct way to call a yclosure property without intermediate variables.

+4
source share
1 answer

Since in PHP a class can have functions and properties, and functions and properties can have the same name.

So when you call:

$x->y();

PHP will look for a function on $xnamed y, and then call it. Instead, you have a property (which contains the function / closure).

This is different from javascript, where both functions and properties are in the same namespace.

+4
source

Source: https://habr.com/ru/post/1613517/


All Articles