Override a trait in PHP

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 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.