Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does invoking callable properties in PHP 7 work?

Tags:

php

php-7

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?

like image 819
Adam Elsodaney Avatar asked May 09 '17 14:05

Adam Elsodaney


People also ask

Are PHP functions callable?

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.

How do you access the properties of an object in PHP?

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 .

How do you check if a function has been called in PHP?

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.


1 Answers

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.

like image 53
Niet the Dark Absol Avatar answered Sep 20 '22 18:09

Niet the Dark Absol