Skip to content
Advertisement

PHP7.3: How can I inherit a protected static property with the thightest possible scope without redeclaring it in the child class?

In the application I’m working on, the Model part of the MVC stack is designed to work trough singletons; each Model has a __getInstanceMethod which is

JavaScript

End result is, if __getInstance() is called twice on the same Model class, it returns the same exact object both times.

I tried to reduce code duplication by moving the __getInstance() method to the Model’s parent class, BaseModel, by editing it like so.

JavaScript

Problem is, I need to manually add a $singleton property to each and every Model class, otherwise I’ll always get returned the instance of the first Model class I called the method on.

JavaScript

Is there a way I can avoid doing that?

Advertisement

Answer

You could switch to an “instance map”, e.g.:

JavaScript

https://3v4l.org/qG0qJ


and with 7.4+ it could be simplified to:

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