PHP Class Customization trait

I’ve written a trait to help with customizing classes behaviors. For example if you have a class A with method getName() but in this method you want to check whether you want the full name to be returned or just the last or first name, the solution will be creating a new method or editing the code. This trait solves it


All you need to do is to add use HasOptions to the desired class




Note: In order to use traits and customize the $options array, the class where you’re adding your $options array needs to a child of the class where HasOptions is used, so the example i gave you will generate error related to $options = [];

[alert type=”warning”]If a trait defines a property then a class can not define a property with the same name unless it is compatible (same visibility and initial value), otherwise a fatal error is issued. Before PHP 7.0.0, defining a property in the class with the same visibility and initial value as in the trait, raised an E_STRICT notice. [/alert]


So keep that in mind.