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

如果实体只是少数类的成员,而不是某些类的成员,那么我想执行一些函数。

有一个称为 instanceof的函数。

但是有没有类似

if ($entity !instanceof [User,Order,Product])
92442 次浏览

This function should do it:

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

So your code is

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

Give them a common interface and then

if (!$entity instanceof ShopEntity)

or stay with

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

I would avoid creating arbitrary functions just to save some characters at a single place. On the other side if you need it "too often", you may have a design flaw? (In the meaning of "too much edge cases" or such)

PHP manual says: http://php.net/manual/en/language.operators.type.php

!($a instanceof stdClass)

This is just a logical and "grammatically" correct written syntax.

!$class instanceof someClass

The suggested syntax above, though, is tricky because we are not specifying which exactly is the scope of the negation: the variable itself or the whole construct of $class instanceof someclass. We will only have to rely on the operator precendence here [Edited, thanks to @Kolyunya].

PHP Operator Precedence

instanceof operator is just before negation then this expression:

!$class instanceof someClass

is just right in PHP and this do that you expect.

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


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

Or you can try these

    $cls = [GlobalNameSpace::class,\GlobalNameSpaceWithSlash::class,\Non\Global\Namespace::class];
if(!in_array(get_class($instance), $cls)){
//do anything
}