INSTANCEOF

کد PHP

<?php
/*
 * 
 * opcode number: 138
 */
$obj = new A();

if (
$obj instanceof A) {
   echo 
'A';
}
?>

opcodeهای PHP

نام تابع: (null)

متغیر ترجمه شده: !0=$obj

line#op fetchextreturn operands
60 ZEND_FETCH_CLASS   :0 'A'
 1 NEW   $1 :0
 2 DO_FCALL_BY_NAME  0   
 3 ASSIGN     !0,$1
84 ZEND_FETCH_CLASS   :4 'A'
 5 ZEND_INSTANCEOF   ~5 !0,$4
 6 JMPZ     ~5,->9
97 ECHO     'A'
108 JMP     ->9
119 RETURN     1
add a note add a note

User Contributed Notes 2 notes

up
5
cody at codysnider dot com
2 years ago
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

?>

Result (CLI, 5.4.4):

use of test() method
Foo
Bar
instanceof Foo
bool(true)
bool(true)
instanceof Bar
bool(false)
bool(true)
subclass of Foo
bool(false)
bool(true)
subclass of Bar
bool(false)
bool(false)
up
5
asdf at asdf dot com
2 years ago
Please note, that you get no warnings on non-existent classes:

<?php
class A() {
}

$a = new A();

$exists = ($a instanceof A); //TRUE
$exists = ($a instanceof NonExistentClass); //FALSE
To Top