PHP中的类切换(instanceof)

jbose2ul  于 2023-02-03  发布在  PHP
关注(0)|答案(3)|浏览(127)

是否可以用开关替换if( .. instanceof ...), elseif(... instanceof ...), ...块?
例如:

<?php
$class = ..... //some class

if($class instanceof SomeClass) {
    //do something
} elseif($class instanceof SomeAnotherClass) {
    //do something else
}
0aydgbwb

0aydgbwb1#

对于instanceof的多态开关(考虑继承):

switch(true) {  
    case $objectToTest instanceof TreeRequest:
        echo "tree request";
        break;
    case $objectToTest instanceof GroundRequest:
        echo "ground request";
        break;
}

对于类名应完全匹配的开关:

$class = get_class($objectToTest);

switch($class) {  
    case 'TreeRequest':
        echo "tree request";
        break;
    case 'GroundRequest':
        echo "ground request";
        break;
}
qlckcl4x

qlckcl4x2#

以下是比较正确的:

$class = get_class($objectToTest);

switch($class) {  
    case TreeRequest::class:
        echo "tree request";
        break;
    case GroundRequest::class:
        echo "ground request";
        break;
}

这样就可以正确地比较名称空间(您不必键入它们),如果名称空间或类名等任何内容发生更改,您将收到一个体面的IDE错误,通知您代码已损坏。

s3fp2yjn

s3fp2yjn3#

使用match表达式,结果如下所示:

return match(get_class($object)) {  
   TreeRequest::class => "tree request",
   GroundRequest::class => "ground request",
   default => "default request"
}

记住它忽略了继承并且只接受当前类。考虑继承的匹配表达式:

return match(true) {  
   $object instanceof TreeRequest=> "tree request",
   $object instanceof GroundRequest => "ground request",
   default => "default request"
}

相关问题