Php Classroom image

Anil  Bist / Professional / Web Technology

 
To post your Question Join Classroom
 
Question No  (4 of 137)
First 1 I 2 I 3 I 4 I 5 I 6 I 7 I 8 I 9 Last
 
Question:-
How can we determine whether a PHP variable is an instantiated object of a certain class?
 
Answer:-

When checking instanceof against a subclass of the class in question, it will return true.

<?php

class Foo {

    public $foobar = 'Foo';
    
    public function test() {
        echo $this->foobar . "\n";
    }

}

class Bar extends Foo {

    public $foobar = 'Bar';

}

$a = new Foo();
$b = new Bar();

echo "use of test() method\n";
$a->test();
$b->test();

echo "instanceof Foo\n";
var_dump($a instanceof Foo); // TRUE
var_dump($b instanceof Foo); // TRUE

echo "instanceof Bar\n";
var_dump($a instanceof Bar); // FALSE
var_dump($b instanceof Bar); // TRUE

echo "subclass of Foo\n";
var_dump(is_subclass_of($a, 'Foo')); // FALSE
var_dump(is_subclass_of($b, 'Foo')); // TRUE

echo "subclass of Bar\n";
var_dump(is_subclass_of($a, 'Bar')); // FALSE
var_dump(is_subclass_of($b, 'Bar')); // FALSE

?>

<?php
$obj = new A();
if ($obj instanceof A) {
   echo 'A';
}
?>

To be able to verify whether a PHP variable is an instantiated object of a certain class we use instanceof.

  
 
 
 
image
Anil  Bist

Skills    Php

Qualifications :- High School - SLV, College/University - Graphic Era Deemed Univ University,
Location :-Dehradun,Dehradun,Uttarakhand,
Description:-

I started my Professional Journey in 2006 with one of the Web Development Company in Bangalore and my 1st framework was "Ruby on Rail" as Web development and delivered around 5+ Projects using this platform. Then came another dimension as JEE/Sturst framework, Gradually I realized that I want to build something on my own and give my passion and energy on creating something different a
Explore

 

  Students (5)

Ask 
image
shubham
Ask 
Monika
Ask 
Anamika
Ask 
Riya
Ask 
image
Pooja
 
 

Recommended Classes

image Anil Bist
I started my Professional Journey in 2006 with one of the Web Development Company in Bangalore an...
Professional
image shweta Pandey
Passionate about LIFE and Learning. Lets explore together better version of "self", &qu...
Professional
image shweta Pandey
Passionate about LIFE and Learning. Lets explore together better version of "self", &qu...
Professional