How to check if not instance of some class in symfony2

Php

Php Problem Overview


I want to execute some functions if entity is member of few classes but not some.

There is a function called instanceof.

But is there something like

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

Php Solutions


Solution 1 - Php

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)

Solution 2 - Php

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].

Solution 3 - Php

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.

Solution 4 - Php

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')));

Solution 5 - Php

function check($object) {
    $deciedClasses = [
        'UserNameSpace\User',
        'OrderNameSpace\Order',
        'ProductNameSpace\Product',
    ];
    
    return (!in_array(get_class($object), $allowedClasses));
}

Solution 6 - Php

Or you can try these

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMirageView Question on Stackoverflow
Solution 1 - PhpKingCrunchView Answer on Stackoverflow
Solution 2 - PhpDragosView Answer on Stackoverflow
Solution 3 - Phpahurt2000View Answer on Stackoverflow
Solution 4 - PhpBruno SchäpperView Answer on Stackoverflow
Solution 5 - Phpyawa yawaView Answer on Stackoverflow
Solution 6 - PhpZukoView Answer on Stackoverflow