XWi*_*ard 5 php interface instanceof
我有以下问题。
我有以下结构:
Interface A {
public function test();
}
class B implements A {
public function test() {
return $something;
}
}
Run Code Online (Sandbox Code Playgroud)
如果我在 C 类中调用:
$someBclass = new B();
if ($someBclass instanceOf A)
Run Code Online (Sandbox Code Playgroud)
从条件来看我是假的。有没有可能如何检查类 b 是否是接口 A 的实例?谢谢
use A;您的示例应该返回 true,我认为您正在测试另一个文件中的接口,并且您的类中缺少C.
此外,您还必须使用完整的命名空间来检查您的类是否是接口的实例。
如果你有这样的界面:
namespace MyNamespace;
Interface A {
public function test();
}
Run Code Online (Sandbox Code Playgroud)
B类是这样的:
namespace MyNamespace;
class B implements A {
public function test() {
return $something;
}
Run Code Online (Sandbox Code Playgroud)
你的 C 类是这样的:
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;
// ...
}
Run Code Online (Sandbox Code Playgroud)
或者您可以添加以下use语句:
namespace MyNamespace\Util;
use MyNamespace\A;
class C {
// ...
}
Run Code Online (Sandbox Code Playgroud)