Using a constant in a php switch in php 5.5.9

允我心安 提交于 2019-12-23 15:16:54

问题


After installing PHP 5.5.9 on Ubuntu 14 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

回答1:


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

could you try :

switch (constant("PHP_OS"))


来源:https://stackoverflow.com/questions/25645533/using-a-constant-in-a-php-switch-in-php-5-5-9

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!