Last Updated: May 25, 2016
·
453
· hvlmnns

check if a class exists within the extending hirachy

PHP middle class instance of checking

My Problem was that i extended a lot of classes from the BaseClass.
But i needed only those classes wich are extending from a certain class (MiddleClass) within the chain
eg:

SecondClass extends ->
    FirstClass extends ->
        BaseClass

ThirdClass extends ->
    SecondClass extends ->
        MiddleClass extends ->
            FirstClass extends ->
                BaseClass

FourthClass extends ->
    SecondClass extends -> 
        MiddleClass extends ->
            FirstClass extends ->
                BaseClass

Since im in a loop, it would not be recommended to do this:

if ($myclass instanceoff ThirdClass || $myclass instanceoff FourthClass) then do;

instead i implemented a method to do this

if ($myclass->isInstanceof(MiddleClass)) then do;

here is how to do it

class BaseClass
{


    public function getInstances($instance = null, $list = array())
    {

        if (is_null($instance)) {
            $instance = $this;
        }

        $parent = get_parent_class($instance);

        if ($parent) {
            $list[] = $parent;
            $list = self::getInstances($parent, $list);
        }

        return $list;
    }

    public function isInstanceOf($class)
    {
        foreach ($this->getInstances() as $instance) {
            if (strpos($instance, $class) !== false) {
                return true;
            }
        }
        return false;
    }

}

class FirstClass extends BaseClass
{

}

class SecondClass extends FirstClass
{

}

$SecondClass = new SecondClass();

$result = $SecondClass->isInstanceOf("FirstClass");

var_dump($result);