Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Switch by class (instanceof) in PHP

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 } 
like image 596
leninzprahy Avatar asked May 04 '16 13:05

leninzprahy


2 Answers

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; } 
like image 77
Ivan Avatar answered Sep 29 '22 19:09

Ivan


The following is more correct:

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

This way namespaces are properly compared (you don't have to type them out) and if anything changes such as the namespace or class name you'll get a decent IDE error informing you that your code is broken.

like image 23
whitebrow Avatar answered Sep 29 '22 19:09

whitebrow