PHP Type Operators


Introduction

In PHP, it is possible to ascertain whether a given variable is an object of a certain class or not. For this purpose PHP has instanceof operator.

Syntax

$var instanceof class

This operator returns a boolean value TRUE of $var is an object of class, otherwise it returns FALSE

Example

In following example, instanceof operator checks whether given object of a user defined testclass

Example

 Live Demo

<?php
class testclass{
   //class body
}
$a=new testclass();
if ($a instanceof testclass==TRUE){
   echo "\$a is an object of testclass";
} else {
   echo "\$a is not an object of testclass";
}
?>

Output

Following result will be displayed

$a is an object of testclass

To check if a certain object is not an instance of class, use ! operator

Example

 Live Demo

<?php
class testclass{
   //class body
}
$a=new testclass();
$b="Hello";
if (!($b instanceof testclass)==TRUE){
   echo "\$b is not an object of testclass";
} else {
   echo "\$b is an object of testclass";
}
?>

Output

Following result will be displayed

$b is not an object of testclass

The instanceof operator also checks whether a variable is object of parent class

Example

 Live Demo

<?php
class base{
   //class body
}
class testclass extends base {
   //class body
}
$a=new testclass();
var_dump($a instanceof base)
?>

Output

Following result will be displayed

bool(true)

It can also asertain whether a variable is an instance of intrface

Example

 Live Demo

<?php
interface base{
}
class testclass implements base {
   //class body
}
$a=new testclass();
var_dump($a instanceof base)
?>

Output

Following result will be displayed

bool(true)

Updated on: 19-Sep-2020

278 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements