Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if not instance of some class in symfony2

Tags:

php

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]) 
like image 419
Mirage Avatar asked Jul 27 '12 05:07

Mirage


People also ask

How do you check if an object is an instance of a particular type?

Using isinstance() function, we can test whether an object/variable is an instance of the specified type or class such as int or list. In the case of inheritance, we can checks if the specified class is the parent class of an object. For example, isinstance(x, int) to check if x is an instance of a class int .

How do you check whether the object is instance of the class derived from it or not?

The java “instanceof” operator is used to test whether the object is an instance of the specified type (class or subclass or interface). It is also known as type comparison operator because it compares the instance with type. It returns either true or false.

How do you check if an object is an instance of a class PHP?

The instanceof keyword is used to check if an object belongs to a class. The comparison returns true if the object is an instance of the class, it returns false if it is not.

Can I use Instanceof?

The instanceof operator in JavaScript is used to check the type of an object at run time. It returns a boolean value if true then it indicates that the object is an instance of a particular class and if false then it is not.


1 Answers

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)

like image 151
KingCrunch Avatar answered Oct 12 '22 08:10

KingCrunch