在PHP中按类(instanceof)切换

时间:2016-05-04 13:27:13

标签: php switch-statement instanceof

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

例如:

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

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

2 个答案:

答案 0 :(得分:53)

有些人喜欢这样:

$class = get_class($objectToTest);

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

或者这个:

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

答案 1 :(得分:12)

以下更正确:

$class = get_class($objectToTest);

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

这样就可以正确比较命名空间(你不必输入它们),如果有任何变化,例如命名空间或类名,你会得到一个体面的IDE错误,通知你你的代码坏了。