Extend a PHP class only if another class is specified

Some may argue that this may be bad practice due to potential inconsistencies, but I wonder how (if possible) I could tell the class about extending another class, but only if it is defined.

I know that this will not work, but what I do is:

class MyClass extends (class_exists('OtherClass') ? OtherClass : null) 

Or maybe a function that will work in the constructor to install the extension, if the class exists.

Of course, I want to avoid.

 if(class_exists('OtherClass')) { class MyClass extends OtherClass { //The class } } else { class MyClass { //The class } } 

.. due to massive code duplication.

I searched the answers on Google and around the site, but didnโ€™t find anything - if I repeated the question, let me know.

+7
source share
1 answer

You can create a middle class class that is created inside class_exists() , but without its own behavior:

 if (class_exists('OtherClass')) { class MiddleManClass extends OtherClass { } } else { class MiddleManClass { } } class MyClass extends MiddleManClass { // The class code here } 

This forces the class hierarchy to include another class, but does not have duplicate code (in fact, does not have code), and the methods inside MyClass can reach OtherClass with parent:: or $this as usual if it was available.

+11
source

Source: https://habr.com/ru/post/1488328/


All Articles