如何检查是否不是symfony2中某个类的实例


78

如果实体是少数几个类的成员但不是某些类的成员,我想执行一些功能。

有一个名为的函数instanceof

但是是否有类似的东西

if ($entity !instanceof [User,Order,Product])

1
instanceof不是函数,而是关键字。不,用PHP的语言没有比这更好的了,您必须自己实现一个函数。
GordonM

Đéo升NAOCóGIAI PHAP RA HON NHI
武·特伦健

Answers:


138

给他们一个通用的界面,然后

if (!$entity instanceof ShopEntity)

或留在

if (!$entity instanceof User && !$entity instanceof Product && !$entity instanceof Order)

我会避免创建任意函数,而只是为了将某些字符保存在一个地方。另一方面,如果您“过于频繁”地需要它,您可能会有设计缺陷?(在“过多情况”的含义中)


63
会不会更好if (!($entity instanceof User))
Daniel W.13年

6
@DanFromGermany没有影响。也许可读性。由你决定。
KingCrunch 2014年

1
@KingCrunch在概念上非常令人困惑,为什么它没有作用?我更喜欢德拉戈斯的回答和合理化。这是我这样做的方式,因为在检查实际实例之前否定要检查的实例似乎很脏。
乔纳森

6
@Jonathan参见php.net/manual/en/language.operators.precedence.php最后,它仅$a+$b+$c与vs有关($a+$b)+$c。曾经尝试过2**3**4 == (2**3)**4吗?;)
KingCrunch '16

确保导入/使用您正在使用instanceof检查的类。例如。因为if ( $entity instanceof Audio )我需要use App\Entity\Audio;。如果不使用要检查的类,PHP不会抛出错误-但是if永远不会触发。

70

PHP手册说:http : //php.net/manual/zh/language.operators.type.php

!($a instanceof stdClass)

这只是一种逻辑上和“语法上”正确的书面语法。

!$class instanceof someClass

但是,上面建议的语法很棘手,因为我们没有指定否定范围的确切范围:变量本身或的整个结构$class instanceof someclass。我们只需要在这里依靠操作员的优越性即可[编辑,感谢@Kolyunya]。


6
这是一个更清洁的解决方案。我敢肯定,有一半人最终因为if (!$entity instanceof ShopEntity)没有直觉而开始寻找这个问题,因为我们中的许多人都将!$entity用作$entity === null
mimoralea 2014年

6
你是什么意思We will only have to rely here on the smart implementation of the PHP parser.?语言规范明确指出,instanceof运算符的优先级高于!运算符。
Kolyunya

2
@ Kolyunya可读性,vs“嗯,这看起来很奇怪..让我查一下php的运算符优先级...好了,这可以检查出来”
Brad Kent

13

PHP运算符优先级

instanceof 运算符在否定之前,则此表达式:

!$class instanceof someClass

在PHP中恰好是正确的,这是您期望的。


正如您提到的,主题演讲是instanceof运算符的优先级高于!,因此该语句给出了真实的结果。谢谢
ako

1

此函数应执行以下操作:

function isInstanceOf($object, Array $classnames) {
    foreach($classnames as $classname) {
        if($object instanceof $classname){
            return true;
        }
    }
    return false;
}

所以你的代码是

if (!isInstanceOf($entity, array('User','Order','Product')));

0
function check($object) {
    $deciedClasses = [
        'UserNameSpace\User',
        'OrderNameSpace\Order',
        'ProductNameSpace\Product',
    ];

    return (!in_array(get_class($object), $allowedClasses));
}

这不能很好地处理继承。
hkoosha

0

或者你可以尝试这些

    $cls = [GlobalNameSpace::class,\GlobalNameSpaceWithSlash::class,\Non\Global\Namespace::class];
    if(!in_array(get_class($instance), $cls)){
        //do anything
    }
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.