在PHP中,可以确定给定的变量是否是某个类的对象。为此,PHP具有instanceof运算符。
$var instanceof class
该运算符返回布尔值TRUE,即$var是类的对象,否则返回FALSE
在下面的示例中,instanceof运算符检查用户定义的testclass的给定对象是否
<?php
class testclass{
//类体
}
$a=new testclass();
if ($a instanceof testclass==TRUE){
echo "\$a is an object of testclass";
} else {
echo "\$a is not an object of testclass";
}
?>输出结果
将显示以下结果
$a is an object of testclass
要检查某个对象是否不是类的实例,请使用!算子
<?php
class testclass{
//类体
}
$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";
}
?>输出结果
将显示以下结果
$b is not an object of testclass
instanceof运算符还会检查变量是否是父类的对象
<?php
class base{
//类体
}
class testclass extends base {
//类体
}
$a=new testclass();
var_dump($a instanceof base)
?>输出结果
将显示以下结果
bool(true)
它还可以确定变量是否为intrface的实例
<?php
interface base{
}
class testclass implements base {
//类体
}
$a=new testclass();
var_dump($a instanceof base)
?>输出结果
将显示以下结果
bool(true)