【问题标题】:instanceof interface return false in phpinstanceof接口在php中返回false
【发布时间】:2016-04-29 23:00:02
【问题描述】:

我有以下问题。

我有以下结构:

Interface A {
public function test(); 
}

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

如果我在 C 类中调用这个:

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

从条件我得到了错误。是否有任何可能性如何检查 b 类是否是接口 A 的实例?谢谢

【问题讨论】:

标签: php interface instanceof


【解决方案1】:

您的示例应该返回 true,我认为您正在测试来自另一个文件的接口,而您的类 C 中缺少 use A;
此外,您必须使用完整的命名空间来检查您的类是否是接口的实例。

如果你有这样的界面:

namespace MyNamespace;

Interface A {
    public function test(); 
}

这样的B类:

namespace MyNamespace;

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

你的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;

    // ...
}

或者您可以添加use 声明:

namespace MyNamespace\Util;

use MyNamespace\A;

class C {
    // ...
}

【讨论】:

    猜你喜欢
    • 2015-07-28
    • 2013-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多