Switch by class (instanceof) in PHP

leninzprahy picture leninzprahy · May 4, 2016 · Viewed 13.4k times · Source

It is possible to replace block of if( .. instanceof ...), elseif(... instanceof ...), ... with switch?

For example:

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

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

Answer

Ivan picture Ivan · May 4, 2016

For a polymorphic switch with instanceof which considers inheritance:

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

For a switch where the class name should match exactly:

$class = get_class($objectToTest);

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