在PHP中按类(instanceof)切换

问题描述 投票:0回答:3

可以用开关代替

if( .. instanceof ...), elseif(... instanceof ...), ...
的块吗?

例如:

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

if($class instanceof SomeClass) {
    //do something
} elseif($class instanceof SomeAnotherClass) {
    //do something else
}
php switch-statement instanceof
3个回答
100
投票

对于带有

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;
}

46
投票

以下说法更正确:

$class = get_class($objectToTest);

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

通过这种方式,可以正确比较命名空间(您不必将它们键入),如果命名空间或类名等发生任何更改,您将收到一个不错的 IDE 错误,通知您代码已损坏。


12
投票

使用

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"
};
© www.soinside.com 2019 - 2024. All rights reserved.