开发者

Switch for comparing different objects

开发者 https://www.devze.com 2023-02-03 08:21 出处:网络
I mostly use the switch case for string values. Can someone confirm if they can be used for equality of complex objects and if the objects are different too. As you can see I\'m not always checking if

I mostly use the switch case for string values. Can someone confirm if they can be used for equality of complex objects and if the objects are different too. As you can see I'm not always checking if $obj1 == some other objects. Both objects can change. Can someone tell me what would be the right syntax for this if it's allowed? I'm not sure what I would put as the switch() input itself.

if ($obj1 == $obj9) 

elseif ($obj5 == $obj9)

elseif ($obj5 == $obj1)

else

new code, would this be correct?

switch (true){
     case $obj1 == $obj9: 
          //do something
          br开发者_开发问答eak;
     case $obj5 == $obj9:
          //do something
          break;
     case $obj5 == $obj1: 
          //do something
          break;
     case default: 
          //do something
          break;  
}


According to PHP Manual, switch-case statement is equal to "if" statement with "==" comparison. So, it does comparison in accordance with these rules. Objects are compared in accordance with objects comparison rules.

BTW switch-case statement is typically used to compare one value against set of several another values, while if-else construction in your question compares 3 pairs of different variables.

0

精彩评论

暂无评论...
验证码 换一张
取 消