-
Notifications
You must be signed in to change notification settings - Fork 7.9k
Description
Description
Traits have support for aliasing as part of the conflict resolution strategy. This does not only allow to change visibility of the imported method but also to import it using a different.
Aliasing the method works as expected but the original method will be copied too. Unless the class defines the exact same method already (which overrules the trait’s method) the alias will cause two methods to be copied from the trait.
<?php
trait Foo {
public function hello(): string
{
return "Hello from Foo!";
}
}
class Bar {
use Foo {
hello as private somethingElse;
}
}
$bar = new Bar();
var_dump($bar->hello());
// Throws
var_dump($bar->somethingElse());
Resulted in this output:
string(15) "Hello from Foo!"
Fatal error: Uncaught Error: Call to private method Bar::somethingElse() from global scope in /in/uAjcv:19
Stack trace:
#0 {main}
thrown in /in/uAjcv on line 19
Process exited with code 255.
A live version is available at https://3v4l.org/uAjcv. It should be noted that the behavior for the visibility change works just fine, importing the method as protected
or private
will correctly change the visibility while maintaining the original method.
The issue at hand is that both the “original” method is copied over and its visibility remains unchanged.
Psalm correctly validates this behavior, but PHPStan incorrectly (up for discussion 😉) flags the call to the original method name as an error. I will open a bug report with PHPStan too.
PHP Version
8.4.3
Operating System
No response