4

i have following problem.

I had following structure:

Interface A {
public function test(); 
}

class B implements A {
    public function test() {
    return $something;
}
}

if I call in class C this:

$someBclass = new B();
if ($someBclass instanceOf A)

From condition I got false. Is there any possibilites how check if class b is instance of interface A? Thank you

XWizard
  • 319
  • 6
  • 17
  • classes are not instances of Interfaces, but implement them: [php:class_implements](http://php.net/manual/de/function.class-implements.php) – Franz Gleichmann Jan 23 '16 at 10:00
  • Should return a true - [Demo](https://3v4l.org/3XDOo) and see [example #4 in the PHP Docs](http://php.net/manual/en/language.operators.type.php) – Mark Baker Jan 23 '16 at 10:02
  • Give a look at this other answer: http://stackoverflow.com/questions/274360/checking-if-an-instances-class-implements-an-interface it could help you. – Igor Scabini Jan 23 '16 at 10:10

1 Answers1

4

Your example should return true, I think you are testing an interface from another file and you are missing the use A; in your class C.
Also you have to use the full namespace to check if your class is an instance of your interface.

If you have an interface like this :

namespace MyNamespace;

Interface A {
    public function test(); 
}

A class B like this :

namespace MyNamespace;

class B implements A {
    public function test() {
    return $something;
}    

And your class C is like this :

namespace MyNamespace\Util;

class C {
    // ...
    $someBclass = new B();

    if ($someClassB instanceof A){
        die('InstanceOf');
    } else {
        die('Not instanceOf');
    }
    // Output: Not instanceOf 

    if ($someClassB instanceof \MyNamespace\A){
        die('InstanceOf');
    }
    // Output: InstanceOf;

    // ...
}

Or you can add the use statement :

namespace MyNamespace\Util;

use MyNamespace\A;

class C {
    // ...
}
chalasr
  • 12,971
  • 4
  • 40
  • 82