instanceof 锟斤拷锟斤拷确锟斤拷一锟斤拷 PHP 锟斤拷锟斤拷锟角凤拷锟斤拷锟斤拷某一锟斤拷 class 锟斤拷实锟斤拷锟斤拷
Example #1 锟斤拷锟斤拷使锟斤拷 instanceof
<?php
class MyClass
{
}
class NotMyClass
{
}
$a = new MyClass;
var_dump($a instanceof MyClass);
var_dump($a instanceof NotMyClass);
?>
锟斤拷锟斤拷锟斤拷锟教伙拷锟斤拷锟斤拷锟�
bool(true) bool(false)
instanceof锟斤拷也锟斤拷锟斤拷锟斤拷确锟斤拷一锟斤拷锟斤拷锟斤拷锟角诧拷锟角继筹拷锟斤拷某一锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷实锟斤拷锟斤拷
Example #2 锟皆继筹拷锟斤拷使锟斤拷 instanceof
<?php
class ParentClass
{
}
class MyClass extends ParentClass
{
}
$a = new MyClass;
var_dump($a instanceof MyClass);
var_dump($a instanceof ParentClass);
?>
锟斤拷锟斤拷锟斤拷锟教伙拷锟斤拷锟斤拷锟�
bool(true) bool(true)
锟斤拷锟揭伙拷锟斤拷锟斤拷锟斤拷欠锟�锟斤拷锟斤拷某锟斤拷锟斤拷锟绞碉拷锟斤拷锟斤拷锟斤拷锟绞癸拷锟�锟竭硷拷锟斤拷锟斤拷锟� not锟斤拷
Example #3 使锟斤拷 instanceof 锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷某锟斤拷锟斤拷锟绞碉拷锟�
<?php
class MyClass
{
}
$a = new MyClass;
var_dump(!($a instanceof stdClass));
?>
锟斤拷锟斤拷锟斤拷锟教伙拷锟斤拷锟斤拷锟�
bool(true)
锟斤拷锟�instanceof也锟斤拷锟斤拷锟斤拷确锟斤拷一锟斤拷锟斤拷锟斤拷锟角诧拷锟斤拷实锟斤拷锟斤拷某锟斤拷锟接匡拷锟侥讹拷锟斤拷锟绞碉拷锟�:
Example #4 锟皆接匡拷使锟斤拷 instanceof
<?php
interface MyInterface
{
}
class MyClass implements MyInterface
{
}
$a = new MyClass;
var_dump($a instanceof MyClass);
var_dump($a instanceof MyInterface);
?>
锟斤拷锟斤拷锟斤拷锟教伙拷锟斤拷锟斤拷锟�
bool(true) bool(true)
锟斤拷然 instanceof 通锟斤拷直锟斤拷锟斤拷锟斤拷锟斤拷一锟斤拷使锟矫o拷锟斤拷也锟斤拷锟斤拷使锟矫讹拷锟斤拷锟斤拷址锟斤拷锟斤拷锟斤拷锟斤拷锟�
Example #5 锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷使锟斤拷 instanceof
<?php
interface MyInterface
{
}
class MyClass implements MyInterface
{
}
$a = new MyClass;
$b = new MyClass;
$c = 'MyClass';
$d = 'NotMyClass';
var_dump($a instanceof $b); // $b is an object of class MyClass
var_dump($a instanceof $c); // $c is a string 'MyClass'
var_dump($a instanceof $d); // $d is a string 'NotMyClass'
?>
锟斤拷锟斤拷锟斤拷锟教伙拷锟斤拷锟斤拷锟�
bool(true) bool(true) bool(false)
锟斤拷锟斤拷锟斤拷锟斤拷谋锟斤拷锟斤拷锟斤拷嵌锟斤拷锟絠nstanceof 锟斤拷锟斤拷锟斤拷锟斤拷锟轿何达拷锟斤拷锟斤拷息锟斤拷锟角凤拷锟斤拷
FALSE
锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷獬o拷锟斤拷锟�
Example #6 锟斤拷 instanceof 锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟�
<?php
$a = 1;
$b = NULL;
$c = imagecreate(5, 5);
var_dump($a instanceof stdClass); // $a is an integer
var_dump($b instanceof stdClass); // $b is NULL
var_dump($c instanceof stdClass); // $c is a resource
var_dump(FALSE instanceof stdClass);
?>
锟斤拷锟斤拷锟斤拷锟教伙拷锟斤拷锟斤拷锟�
bool(false) bool(false) bool(false) PHP Fatal error: instanceof expects an object instance, constant given
然锟斤拷 instanceof 锟斤拷使锟矫伙拷锟斤拷一些锟斤拷锟斤拷锟斤拷锟斤拷私狻o拷锟� PHP 5.1.0 之前锟斤拷锟斤拷锟揭拷锟斤拷锟斤拷锟斤拷锟斤拷撇锟斤拷锟斤拷冢锟�instanceof 锟斤拷锟斤拷锟� __autoload()锟斤拷锟斤拷锟解,锟斤拷锟斤拷锟斤拷锟矫伙拷斜锟阶帮拷锟斤拷锟斤拷锟斤拷锟揭伙拷锟斤拷锟斤拷锟斤拷锟斤拷蟆?锟斤拷锟酵拷锟绞癸拷枚锟教拷锟斤拷锟斤拷没锟斤拷锟揭伙拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷址锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷芸锟斤拷锟斤拷锟斤拷锟斤拷猓�
Example #7 锟斤拷锟斤拷 PHP 5.0 锟斤拷 instanceof 锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷液锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷锟�
<?php
$d = 'NotMyClass';
var_dump($a instanceof $d); // no fatal error here
?>
锟斤拷锟斤拷锟斤拷锟教伙拷锟斤拷锟斤拷锟�
bool(false)
instanceof 锟斤拷锟斤拷锟斤拷锟� PHP 5 锟斤拷锟斤拷锟侥★拷锟节达拷之前锟斤拷 is_a()锟斤拷锟斤拷锟角猴拷锟斤拷 is_a() 锟斤拷锟斤拷锟斤拷锟斤拷锟斤拷 instanceof 锟斤拷锟斤拷恕锟阶拷锟斤拷锟� PHP 5.3.0 锟斤拷锟街恢革拷使锟斤拷 is_a() 锟剿★拷
锟轿硷拷 get_class() 锟斤拷 is_a()锟斤拷