-2

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.

Jaquarh
  • 6,493
  • 7
  • 34
  • 86
  • Down-vote? Explain how this question is asked wrong rather than just down-voting, so I can improve it. – Jaquarh Dec 20 '16 at 13:03
  • `$obj` is an *instance* of a class (it could be any class), `$nsp` is a string which holds the *namespace* and *class name* like `\App\Com\Foo`.. I want to basically use that string to check the array of objects and return the corresponding instance @deceze [see what i mean](https://3v4l.org/knhjm) – Jaquarh Dec 20 '16 at 13:08

2 Answers2

1

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)
deceze
  • 510,633
  • 85
  • 743
  • 889
  • appreciated, I've been Googling this for ages. Maybe I'm just having one of them dumb days, thanks a lot! – Jaquarh Dec 20 '16 at 13:11
1

It's the other way around:

if ($obj instanceof $nsp)
sepehr
  • 17,110
  • 7
  • 81
  • 119