Looking for more information on how to do PHP the right way? Check out PHP: The Right Way

Freek Van der Herten:
A trait to dynamically add methods to a class
Sep 25, 2017 @ 15:50:51

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.

tagged: package macroable macro trait laravel standalone

Link: https://murze.be/2017/09/trait-dynamically-add-methods-class/


Trending Topics: