Subscribe to PHP Freaks RSS

Freek Van der Herten: A trait to dynamically add methods to a class

syndicated from www.phpdeveloper.org on September 25, 2017

Freek Van der Herten has posted about a new package that's essentially a stand-alone version of Laravel's own "macros" functionality available via a package: macroable.

We recently released our newest package called macroable. It contains a trait that, when applied to class, can dynamically add methods to that class. This trait is basically a stand alone version of the macroable trait in Laravel. In this post I’d like to show you how you can use it, how it works behind the scenes and explain why we created it.

He then gives examples of how it can be used to add a new simple method (essentially a "named closure") and using the "mixin" functionality to add multiple at once. He wraps up the post with a look at how it works behind the scenes, adding the items to a "macros" list and then looking them up if they're not defined on the class.