The following is more correct:$class = get_class($objectToTest); switch($class) { case TreeRequest::class: echo "tree request"; break; case GroundRequest::class: echo "ground request";…
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;
}
1 Comment
Ольга · 2020-07-24 at 07:30
so to minimize the network traffic, you keep these objects as light weight as possible. When you receive a packet, you need to know what to do with it, so I’m making this determination based on what type of packet object the passed object is an instanceof. This approach is the same undertaken in the examples included with Kryonet’s distribution. I’d love to clean up the hideous class that translates these packets into action, and figure a switch statement would at least make it look moderately more organized.