instanceof使用细节

<?php
declare(strict_types=1);
ini_set('display_errors', 'On');
ini_set('error_reporting', E_ALL);


function v(mixed $value, mixed ...$values): void
{
    ob_start();
    var_dump($value);
    echo ob_get_clean();

    foreach ($values as $v) {
        v($v);
    }
}


/**
 * RuntimeExceptionInterface1接口
 */
interface RuntimeExceptionInterface1
{
}


/**
 * RuntimeExceptionInterface2接口
 */
interface RuntimeExceptionInterface2
{
}


/**
 * MyRuntimeException类
 */
class MyRuntimeException extends RuntimeException implements RuntimeExceptionInterface1, RuntimeExceptionInterface2
{
}


$myRuntimeException = new MyRuntimeException('PHP是世界上最好の语言');
v($myRuntimeException instanceof MyRuntimeException);         // bool(true)
v($myRuntimeException instanceof RuntimeException);           // bool(true)
v($myRuntimeException instanceof Exception);                  // bool(true)
v($myRuntimeException instanceof RuntimeExceptionInterface1); // bool(true)
v($myRuntimeException instanceof RuntimeExceptionInterface2); // bool(true)


//========== 总结 ==========//
// 1、instanceof用于判断一个变量是否属于某一类(包括本类、父类、爷类)的实例,也可用于判断是否实现某一接口。

Copyright © 2024 码农人生. All Rights Reserved