Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is type callable supported with typed properties?

I searched reasons for this but wasn't able to find any reason for this.

I tried to create a typed property with the type 'callable'. But PHP gives me a fatal error "cannot have type callable". In the RFC, it is not mentioned, that callable is not an allowed type for the property type hints. Instead there are examples, where the use of 'callable' for typed properties are used.

See: https://wiki.php.net/rfc/typed-properties

What is the reason for this? Are there any discussions on this topic online?

like image 780
mscho Avatar asked Sep 14 '19 13:09

mscho


1 Answers

Proposal in provided link https://wiki.php.net/rfc/typed-properties has status declined.

The proposal implemented in php7.4 is here https://wiki.php.net/rfc/typed_properties_v2 and there's an explanation about callable:

The callable type is not supported, because its behavior is context dependent The following example illustrates the issue:

class Test {
    public callable $cb;

    public function __construct() {
        // $this->cb is callable here
        $this->cb = [$this, 'method'];
    }

    private function method() {}
}


$obj = new Test;
// $obj->cb is NOT callable here
($obj->cb)();

This means that it is possible to write a legal value to a property and then proceed to read an illegal value from the same property. This fundamental problem of the callable pseudo-type is laid out in much more detail in the consistent callables RFC.

The recommended workaround is to instead use the Closure type, in conjunction with Closure::fromCallable(). This ensures that the callable will remain callable independent of scope. For a discussion of alternative ways to handle the callable issue, see the Alternatives section.

List of all implemented proposals for php7.4 is here https://wiki.php.net/rfc#php_74.

like image 109
u_mulder Avatar answered Nov 09 '22 00:11

u_mulder