Skip to content

Aliasing a trait method imports the method with the original name too #17738

@dtdesign

Description

@dtdesign

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      pFad - Phonifier reborn

      Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

      Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


      Alternative Proxies:

      Alternative Proxy

      pFad Proxy

      pFad v3 Proxy

      pFad v4 Proxy