instanceof 是 PHP 中用于检查对象是否属于某个类或接口的关键字
class Animal {}
class Dog extends Animal {}
$animal = new Animal();
$dog = new Dog();
if ($animal instanceof Dog) {
echo "The animal is a dog.";
} else {
echo "The animal is not a dog.";
}
if ($dog instanceof Animal) {
echo "The dog is an animal.";
} else {
echo "The dog is not an animal.";
}
?>
在这个例子中,我们定义了两个类:Animal 和 Dog。Dog 类继承了 Animal 类。我们创建了两个对象:$animal 和 $dog。然后我们使用 instanceof 关键字检查这两个对象是否属于相应的类或接口。
第一个 if 语句检查 $animal 是否是 Dog 类的实例。因为 $animal 是通过 new Animal() 创建的,而不是直接通过 new Dog() 创建的,所以 $animal 不是 Dog 类的实例。因此,第一个 if 语句将输出 “The animal is not a dog.”。
第二个 if 语句检查 $dog 是否是 Animal 类的实例。因为 $dog 是通过 new Dog() 创建的,而 Dog 类继承了 Animal 类,所以 $dog 是 Animal 类的实例。因此,第二个 if 语句将输出 “The dog is an animal.”。
以上就是关于“instanceof php用法是什么”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm