Override a trait in PHP

php logo

I encountered a situation recently in which I wanted to change the method signature for a method that was injected into a class via a trait, namely changing the default parameter. I wanted to do this so I didn't have to pass in the new default parameter every place that I called this method on this particular class.

Overriding the method, was easy enough. As soon as a new method is declared in a class with the same name, the trait method is overridden. The tricky part was calling the 'parent' method from the 'child' method, so I didn't have to duplicate the logic inside my new method. I tried parent::methodName() and TraitName::methodName() before running off to the google machine to learn the proper way to do this.

It turns out that it is as easy as creating an alias for the trait method name in the "Use" statement, which made perfect sense after I saw it.

So, if this is the trait that you want to use and override:

trait SomeTrait {
    public function someMethod(string $key = 'Id')
    {
        // logic
        return $resultOfLogic;
    }
}

Just give an alias to the trait method name when "Using" the trait as such:

use SomeTrait {someMethod as public traitSomeMethod;}

Here is a full example:

<?php

class Something
{
    use SomeTrait {someMethod as public traitSomeMethod;}

    public function someMethod(string $key = 'Name')
    {
        return $this->traitSomeMethod($key);
    }
}

So now I could call this method on any instantiation of this class without explicitly passing the default $key every time I needed to call it. Also, I had the added benefit of not having to duplicate the logic, keeping things DRY and ensuring that any changes made to the traits logic would 'bubble down' to the concrete implementation of the class.

If you liked this post, you can subscribe to the rss feed or follow me @ToddEidson on Twitter to be notified of future blog posts.

Date Published: 23 February, 2019

Tags: php

About Todd

Full stack application developer. Life-long learner. Pragmatic programmer. Believer in clean coding. Proponent for extensible and reusable code. Hobbies include (very) amateur photography, collecting old jazz records and going to live music performances.

North Central Ohio, US
toddeidson[dot]info

Obligatory Disclaimer

All opinions are my own, probably wrong, and subject to change without notice.

© 2017-2019 Todd Eidson. All content is licensed under the Creative Commons Attribution-ShareAlike 4.0 International License.

Hosted on linode