Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 529
MDEV Avatar asked Jun 26 '13 15:06

MDEV


1 Answers

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.

like image 66
complex857 Avatar answered Nov 08 '22 13:11

complex857