【发布时间】:2012-04-08 18:04:37
【问题描述】:
switch (true){
case stripos($_SERVER['SERVER_NAME'],"mydomain.com", 0) :
//do something
break;
/*
stripos returns 4 ( which in turn evaluates as TRUE )
when the current URL is www.mydomain.com
*/
default:
/*
stripos returns 0 ( which in turn evaluates as FALSE )
when the current URL is mydomain.com
*/
}
当 stripos 在大海捞针中找到针时,返回 0 或向上。 当 stripos 没有找到针时,它返回 FALSE。这种方法可能有一些优点。但我不喜欢那样!
我来自 VB 背景。在那里,instr 函数(相当于 strpos)在找不到针头时返回 0,如果找到针头则返回 1 或以上。
所以上面的代码永远不会导致问题。
您如何在 PHP 中优雅地处理这种情况?这里的最佳实践方法是什么?
另外,换个说法,你觉得使用
switch(true)
这是编写代码的好方法吗?
【问题讨论】:
-
if(stripos(....) === false){ ...} else { ... } 有什么问题
-
没有错。所以您建议将其编码为 case (stripos($_SERVER['SERVER_NAME'],"mydomain.com", 0) === TRUE) 这是最优雅的方式吗?
-
我会使用 if 语句。使用 switch() 有什么意义?不过,我离 php 专家还差得很远!
-
您的
switch不起作用。如果您想避开===false布尔驼峰,请使用strstr()并让 PHP 字符串评估处理它。 -
开关出了什么问题?语法错误?
标签: php coding-style strpos boolean-operations