ZetCode

PHP instanceof 运算符

最后修改于 2025 年 4 月 16 日

PHP instanceof 关键字用于确定一个对象是否是特定类或接口的实例。 这对于面向对象 PHP 编程中的类型检查至关重要。 这个运算符有助于确保类型安全。

基本定义

instanceof 运算符检查一个对象是否是类的实例。 它还可以验证一个对象是否实现了接口。 如果对象与指定的类型匹配,则运算符返回 true。

语法:$object instanceof ClassName$object instanceof InterfaceName。 左操作数是要检查的对象。 右操作数是类/接口名称。

该运算符也适用于父类和继承的接口。 在方法调用之前,它对于多态性和类型检查很有用。

基本类检查

此示例演示如何检查一个对象是否是类的实例。

basic_instanceof.php
<?php

class Car {}
$myCar = new Car();

if ($myCar instanceof Car) {
    echo "The object is a Car.";
} else {
    echo "The object is not a Car.";
}

该代码创建一个 Car 对象并检查其类型。 instanceof 运算符返回 true,因为 $myCar 是 Car 实例。 这是最简单的用例。

接口实现检查

此示例显示如何检查一个对象是否实现了接口。

interface_check.php
<?php

interface Logger {
    public function log(string $message): void;
}

class FileLogger implements Logger {
    public function log(string $message): void {
        file_put_contents('log.txt', $message, FILE_APPEND);
    }
}

$logger = new FileLogger();

if ($logger instanceof Logger) {
    echo "The object implements Logger interface.";
    $logger->log("Test message");
}

该代码定义了一个 Logger 接口和 FileLogger 实现。 instanceof 检查在调用接口方法之前验证接口实现。 这确保了类型安全。

继承检查

此示例演示检查父子类关系。

inheritance_check.php
<?php

class Animal {}
class Dog extends Animal {}

$dog = new Dog();

if ($dog instanceof Animal) {
    echo "Dog is an Animal (parent class check).";
}

if ($dog instanceof Dog) {
    echo "Dog is a Dog (same class check).";
}

代码显示 instanceof 对实际类及其父类都返回 true。 这在使用多态对象时很有用。 检查贯穿整个继承链。

检查多个类

此示例显示如何针对多个可能的类检查一个对象。

multiple_classes.php
<?php

class Shape {}
class Circle extends Shape {}
class Square extends Shape {}

function draw(Shape $shape): void {
    if ($shape instanceof Circle) {
        echo "Drawing a circle.";
    } elseif ($shape instanceof Square) {
        echo "Drawing a square.";
    } else {
        echo "Drawing unknown shape.";
    }
}

draw(new Circle());
draw(new Square());

该代码演示了不同形状类型的运行时类型检查。 该函数接受任何 Shape,但根据具体类型表现不同。 这种模式在多态代码中很常见。

检查非对象

此示例显示 instanceof 对非对象值的行为。

non_objects.php
<?php

class Test {}

$values = [
    new Test(),
    'hello',
    42,
    null,
    function() {}
];

foreach ($values as $value) {
    if ($value instanceof Test) {
        echo "Test object\n";
    } else {
        echo gettype($value) . " is not a Test object\n";
    }
}

该代码使用 instanceof 测试各种值类型。 只有实际的 Test 对象通过了检查。 其他类型(字符串、整数、null、闭包)失败。 运算符仅适用于对象。

命名空间类

此示例演示了如何将 instanceof 与命名空间类一起使用。

namespaces.php
<?php

namespace MyApp\Models;

class User {}

$user = new User();

if ($user instanceof User) {
    echo "Instance of User (relative check).";
}

if ($user instanceof \MyApp\Models\User) {
    echo "Instance of fully qualified User.";
}

代码显示了两种检查命名空间类的方法。 如果在同一个命名空间中,可以直接使用类名。 对于跨命名空间检查,请使用完全限定的名称。 这两种方法都有效。

与 Traits 一起使用

此示例演示了如何使用 instanceof 检查 trait 的使用情况。

traits.php
<?php

trait Loggable {
    public function log(string $message): void {
        echo $message;
    }
}

class Product {
    use Loggable;
}

$product = new Product();

if ($product instanceof Product) {
    echo "Product instance (class check).";
}

// Note: You cannot directly check for traits with instanceof

代码显示 instanceof 仅检查类和接口,而不是 trait。 要检查 trait 的使用情况,您需要使用其他方法,例如 method_exists。 Traits 是编译器辅助的复制粘贴,而不是运行时类型。

最佳实践

来源

PHP instanceof 文档

本教程介绍了 PHP 的 instanceof 运算符,并通过实际示例展示了在各种场景中进行类、接口和继承检查。

作者

我叫 Jan Bodnar,是一位充满激情的程序员,拥有丰富的编程经验。 自 2007 年以来,我一直在撰写编程文章。 迄今为止,我撰写了 1,400 多篇文章和 8 本电子书。 我拥有超过十年的编程教学经验。

列出 所有 PHP 教程