Consider the following code:
interface Doll
{
/**
* @return string
*/
function __invoke();
}
class LargeDoll
{
private $inner;
function __construct(Doll $inner)
{
$this->inner = $inner;
}
function __invoke()
{
return $this->inner() . ' world';
}
}
This won't work because it is expecting $this->inner
to be a method, rather than a callable property.
Then it occurred to me, just like having (new LargeDoll)();
would work, what about if the property was wrapped in paranthesis also? So I tested it on 3v4l:
return ($this->inner)() . ' world';
And found that it works for PHP 7, but not for previous versions.
However, I can't find any mention of this in the changelogs.
Where can I find more information about this feature?
The is_callable() function checks whether the contents of a variable can be called as a function or not. This function returns true (1) if the variable is callable, otherwise it returns false/nothing.
Within class methods non-static properties may be accessed by using -> (Object Operator): $this->property (where property is the name of the property). Static properties are accessed by using the :: (Double Colon): self::$property .
is_callable can be used to check if a function exists like so: function foo() { } echo (int)is_callable('foo'); echo (int)is_callable('bar'); The example code above declares a function called foo() and then uses is_callable by passing in the names of functions to check for. 'foo' exists and 'bar' doesn't.
The ability to use IIFE's (which ($this->inner)()
effectively is) was added as part of the Uniform Variable Syntax RFC by Nikita Popov, which was implemented in PHP7.
It's a consequence of better variable syntax handling in the parser. Considering one of the goals of PHP7 was to overhaul syntax parsing, I think they've achieved some real progress there.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With