php 如何检查symfony2中是否不是某个类的实例
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11682126/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check if not instance of some class in symfony2
提问by Mirage
I want to execute some functions if entity is member of few classes but not some.
如果实体是少数类的成员但不是某些类,我想执行一些函数。
There is a function called instanceof.
有一个函数叫做instanceof.
But is there something like
但是有没有像
if ($entity !instanceof [User,Order,Product])
回答by KingCrunch
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)
我会避免创建任意函数只是为了在一个地方保存一些字符。另一方面,如果你“太频繁”需要它,你可能有设计缺陷?(“边缘情况太多”之类的意思)
回答by Dragos
PHP manual says: http://php.net/manual/en/language.operators.type.php
PHP手册说: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].
但是,上面建议的语法很棘手,因为我们没有指定否定的确切范围:变量本身还是$class instanceof someclass. 我们只需要依赖这里的运算符优先级[编辑,感谢@Kolyunya]。
回答by ahurt2000
instanceofoperator is just before negation then this expression:
instanceof运算符就在否定之前,然后这个表达式:
!$class instanceof someClass
is just right in PHP and this do that you expect.
在 PHP 中恰到好处,这正是您所期望的。
回答by Bruno Sch?pper
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')));
回答by yawa yawa
function check($object) {
$deciedClasses = [
'UserNameSpace\User',
'OrderNameSpace\Order',
'ProductNameSpace\Product',
];
return (!in_array(get_class($object), $allowedClasses));
}
回答by Zuko
Or you can try these
或者你可以试试这些
$cls = [GlobalNameSpace::class,\GlobalNameSpaceWithSlash::class,\Non\Global\Namespace::class];
if(!in_array(get_class($instance), $cls)){
//do anything
}

