Return an object that is an instanceof a string

170 views Asked by At

I am creating a Dependency Injection factory class which allows me to rewrite instances outside and inside the class without having to keep overwriting it.

The issue I have is when I call the instanceof on the object referring the namespace like so:

if($nsp instanceof $obj)
{
    return $obj::getInstance();
}

It always returns false. For example, if there is a Test object inside the namespace \App\Com it would still return false. (See it working properly here)

If you cannot visit the above link, I have a protected $_case which holds an array of pre-instanced objects. Then the method looks like this:

public function using($nsp)
{
    foreach($this->_case as $obj)
    {
        if($nsp instanceof $obj)
        {
            return $obj::getInstance();
        }
    }
    throw new \Exception("Call to $nsp did not match any libraries.");
}

And can be called / used like this:

Service::getInstance()->using('SomeNamespace\SomeObject');

Any help would be greatly appreciated, the documentation explains this concept deeper.

2

There are 2 answers

1
deceze On BEST ANSWER

Your test boils down to this:

'SomeNamespace\SomeObject' instanceof $someObj

Well, a string is never an instance of a class. It appears you have the operands backwards, and what you want is:

if ($obj instanceof $nsp)
0
sepehr On

It's the other way around:

if ($obj instanceof $nsp)