我在我正在研究的投资组合网站的标题中有一个小的switch语句,它管理哪个链接显示在哪个页面上。 $ id的值来自GET变量,即 - '?id = index'。
switch($id) {
case "index":
//Show links to content
case !"index":
//Show link to index
case !"about":
//show link to about page
}
问题是NOT运算符在最后两种情况下不起作用。我希望索引的链接显示用户何时不在索引页面上,同样显示about页面。目前,所有链接都显示在索引页面上(当$ id ==“index”时),NONE显示在任何其他页面上。
为什么会这样?
答案 0 :(得分:5)
就是这样,因为它应该如此。
switch
使用==
运算符进行比较。所以在第二种情况下,你实际上在测试是否
$id == (!"index")
由于任何字符串为false
且不为真,因此true
将始终评估为false
。
这意味着,在您的情况下,最好使用if
和else
。
答案 1 :(得分:0)
很抱歉,但您尝试做的只是switch
/ case
构造的有效语法。
您最接近所需的是使用default
选项。这类似于最终的case
选项,它处理前面任何case
未捕获的所有值。
switch($id) {
case "index":
//Show links to content
case "about":
//Show link to about page
default:
//show link to default page.
}
另外 - 不要忘记每个break;
块末尾的case
,否则它会掉到下一个块,这可能会导致一些意想不到的错误。
答案 2 :(得分:0)
!"index"
可能会评估为false
(但我很惊讶它不会导致语法错误)并且您实际上会有这样的陈述:
switch($id){
case "index": //...
case false: // ...
case false: // ...
}
当您想使用switch
时,您需要这样做:
switch($id){
case "index": // ...
case "about": // ...
default:
// Additional statements here, note that $id != "index" is already covered
// by not entering into case "index"
}
答案 3 :(得分:0)
switch case不接受复杂的表达式。不! operator是逻辑运算符。它适用于这样的表达式。
!$x; // true if $x = false
或比较运算符:
$a != $b; // Not equal
// or
$a !== $b // not identical
来自手册。
switch语句的case表达式可以是任何表达式 计算结果为简单类型,即整数或浮点数 数字和字符串。除非它们,否则不能在此使用数组或对象 被解除引用到一个简单的类型。
答案 4 :(得分:0)
你的代码正在做的是将$ id与三个值进行比较:“index”,!“index”(无论它意味着什么)和!“about”。
我不确定你的做法。你应该尝试if / else或三元运算符。
希望它有所帮助。
答案 5 :(得分:0)
Switch不提供自定义运算符。
switch ( $id ) {
case 'index':
// $id == 'index'
break;
case 'about':
// $id == 'about'
break;
case 'help':
case 'info':
// $id == 'info' or $id == 'help'
break;
default:
// all other cases
}
答案 6 :(得分:0)
你肯定能解决这个问题:
switch($id){
case ($id != 'index'):
echo 'this is not index';
break;
case 'index':
echo 'this is index';
break;
case 'foo':
echo 'this is foo!';
break;
default:
break;
}
然而,这个例子是有缺陷的,因为第一个case语句只会捕获任何不是'index'的东西,因此你不应该看到'foo'的情况,也不会看到默认语句