在 PHP 中按类(实例)切换

2022-08-30 11:25:10

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

例如:

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

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

答案 1

对于考虑继承的多态开关: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;
}

答案 2

以下更正确:

$class = get_class($objectToTest);

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

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


推荐