Switch with instanceof in PHP

There are situations where you need to check what class an object is. The easiest thing is just checking that with instanceof and a simple if statement. But that doesn’t look that good if you’ve got many cases:

if($objectToTest instanceOf TreeRequest) {
	echo "tree request";
} elseif($objectToTest instanceOf GroundRequest) {
	echo "ground request";
} elseif($objectToTest instanceOf LocationRequest) {
	echo "location request";
} elseif($objectToTest instanceOf SituationRequest) {
	echo "situation request";
}

For those cases switch case is the right branching mechanism.

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

On the other hand, you see the problem. You loose the comprehensibility within your IDE when you start using strings to compare. Which you’re doing as soon as you’re using get_class which returns a string.

There is a neat little trick[1] to use switch case without loosing the comprehensibility:

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