3

After installing PHP 5.5.9 on Ubuntu 14.04 (Trusty Tahr), I found this strange behavior with a switch statement and the PHP_OS constant.

I presume that in PHP 5.5.9 the switch statement is also checking for the same type (===)?

Or is it a PHP bug?

echo PHP_OS; // Linux
$os = PHP_OS;

switch (PHP_OS) {
    case "WINNT":
        echo 'Windows';
        break;
    case "Linux":
        echo 'Linux';
        break;
    default:
        echo 'Default';
        break;
}
// Default

switch ((string) PHP_OS) {
    case "WINNT":
        echo 'Windows';
        break;
    case "Linux":
        echo 'Linux';
        break;
    default:
        echo 'Default';
        break;
}
// Default

switch ($os) {
    case "WINNT":
        echo 'Windows';
        break;
    case "Linux":
        echo 'Linux';
        break;
    default:
        echo 'Default';
        break;
}
// Linux
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Asa Carter
  • 2,207
  • 5
  • 32
  • 62

2 Answers2

2

PHP switches use loose comparison like ==, so it should match.

Try:

switch (constant("PHP_OS"))
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
matwr
  • 1,548
  • 1
  • 13
  • 23
0

for those who want to have a solution for class constants we can use this method:

switch($var){
        case get_class_vars('CLASSNAME')['CONST_CLASS']:
break;
Snoozer
  • 585
  • 1
  • 8
  • 16