如果实体是少数几个类的成员但不是某些类的成员,我想执行一些功能。
有一个名为的函数instanceof。
但是是否有类似的东西
if ($entity !instanceof [User,Order,Product])
Answers:
给他们一个通用的界面,然后
if (!$entity instanceof ShopEntity)
或留在
if (!$entity instanceof User && !$entity instanceof Product && !$entity instanceof Order)
我会避免创建任意函数,而只是为了将某些字符保存在一个地方。另一方面,如果您“过于频繁”地需要它,您可能会有设计缺陷?(在“过多情况”的含义中)
if (!($entity instanceof User))?
$a+$b+$c与vs有关($a+$b)+$c。曾经尝试过2**3**4 == (2**3)**4吗?;)
if ( $entity instanceof Audio )我需要use App\Entity\Audio;。如果不使用要检查的类,PHP不会抛出错误-但是if永远不会触发。
PHP手册说:http : //php.net/manual/zh/language.operators.type.php
!($a instanceof stdClass)
这只是一种逻辑上和“语法上”正确的书面语法。
!$class instanceof someClass
但是,上面建议的语法很棘手,因为我们没有指定否定范围的确切范围:变量本身或的整个结构$class instanceof someclass。我们只需要在这里依靠操作员的优越性即可[编辑,感谢@Kolyunya]。
if (!$entity instanceof ShopEntity)没有直觉而开始寻找这个问题,因为我们中的许多人都将!$entity用作$entity === null。
We will only have to rely here on the smart implementation of the PHP parser.?语言规范明确指出,instanceof运算符的优先级高于!运算符。