php-src icon indicating copy to clipboard operation
php-src copied to clipboard

__invoke magic method doesn't work

Open linescrow opened this issue 4 years ago • 2 comments

Description

The following code:

<?php
class UserName
{
    private readonly string $value;

    public function __construct(string $value)
    {
        $this->value = $value;
    }
    public function __invoke()
    {
        return $this->value;
    }
}

class User
{
    public UserName $name;

    public function __construct(string $name)
    {
        $this->name = new UserName($name);
    }
}

// this is run
$name = new UserName('sample');
var_dump( $name() );

// this is not run...
$user = new User('hoge');
var_dump( $user->name() );

Resulted in this output:

But I expected this output instead:

PHP Version

PHP 8.1.2

Operating System

Ubuntu 20.04

linescrow avatar Feb 15 '22 16:02 linescrow

you need parenthesis around $user->name, otherwise you call name method instead of the Closure from the property, see https://3v4l.org/KB9GY

mvorisek avatar Feb 15 '22 16:02 mvorisek

thank you very much!!

linescrow avatar Feb 15 '22 17:02 linescrow