Search code examples
phpclassoopextend

Extend PHP Class only if other class is defined


Some may argue that this could be bad practice due to potential inconsistencies, however, I am wondering how (if possible) I could tell a class to extend another class, but only if it's defined.

I'm aware this doesn't work, but what I'm effectively after is:

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

Or maybe a function that would run in the constructor to set up the extend if the class exists.

I of course want to avoid..

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

.. because of the massive duplication of code.

I've looked for answers on Google and around the site, but found nothing - if I have duplicated a question however, do let me know.


Solution

  • You could create a middle-man class that's created inside the class_exists() condition, 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 makes the class hierarchy include one more class, but has no duplicated code (has no code actually) and methods inside MyClass can reach the OtherClass with parent:: or $this as usual if it was available.