Back to Top

What is the instanceof operator and how do I use it?

What is the instanceof operator and how do I use it

PHP is now widely used service environment.The instanceof operator was introduced in PHP 5. The datatype of the variable passed to the method is uncertain in PHP. So it is difficult to determine whether some of the operations can be run. Before PHP5, is_a () function was used instead of instanceof operator but later is_a () is discarded and replaced with instanceof operator.

Using instanceof operator can determine whether the current instance can have such a form. Using the instanceof operator, the current instance of the current class, parent class, and the interface has been achieved when the comparison returns TRUE.

What is the Instanceof Operator

The Variable defined within a class called instance variable and method contains code so method and variable defined within a class are called the member of the class.The instanceof operator feature is added to make things easier to read and it’s like an existing built-in function is_a() which is deprecated now.instanceof is used like a logical binary operator.

The instanceof operator shows instantiation and the benefits of using instanceof operator are, first determine the instance, rather than directly casts the case of type conversion.

How to use the Instanceof Operator?

You can execute the following example to understand the concept of the instanceof operator.

The above example display ‘Square is a rectangle’.Here I have used __CLASS__ which is a special constant that gives the name of the current class.

Also Read:Polymorphism in PHP

However,instanceof is an operator and therefore It can be used in expressions in conjunction with other operators like the ! [negation] operator. so its allows to easily write a heckIfNotRectangle() function

Note: instanceof operator also checks, if an object implements an interface which is
like an is-a relationship.

At the end,if you do not know the server environment, it is recommended that you use instanceof operator in order to avoid unnecessary trouble.

Have you used instanceof operator in your application? I’d love to hear about it in the comments.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Most Popular Posts

To prevent caching in web browser

Posted on 12 years ago

Bhumi

AWS Cloud Database Migration Service

Posted on 7 years ago

Bhumi