Skip to content
Advertisement

The correct implementation option is using the magic method __call()

There is a Controller class that contains the magic __call() method, which, when passing an argument, gets a name and creates an instance of the corresponding name. The properties $this of the Controller class are passed to the constructor of this class in order to use the req() function.

For example, I recreated the situation from production using examples of 3 classes.

JavaScript

In PHPDoc, I have defined the methods that can be called.

JavaScript

All this is correct. HOWEVER, when creating an instance of a class, you can call the req() function, and this is only allowed in predefined classes from PHPDoc.

Good:

JavaScript

Q: How do I avoid this? Create a trait for this to use in predefined classes, or make a wrapper over the Controller class, and inherit from it already? Comrades, what do you recommend in this situation?

Advertisement

Answer

You can use traits. Traits are exclusively for code reuse and control without any kind of class inheritance. Instead of you extending a class and collecting all its features (some may be unnecessary), traits can help you control this flow of functions, as well as collect information from the class that extends the class you use trait.

Trait example:

JavaScript

Use trait in classes One and Two, it should work:

JavaScript

You can also require the trait file if you are not using autoload.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement