php-src
php-src copied to clipboard
__invoke magic method doesn't work
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
you need parenthesis around $user->name, otherwise you call name method instead of the Closure from the property, see https://3v4l.org/KB9GY
thank you very much!!