如果在PHP中还有其他的那么短?
发布时间:2020-12-13 22:05:08 所属栏目:PHP教程 来源:网络整理
导读:我正在寻找一些简写if / else代码,但不像$var? $a:$b它不需要’else’之类的返回值.我想要的基本上是这个,但更短: $myVariable = "abc";echo $myVariable ? $myVariable : "hello";echo $myVariable ? "hello" : $myVariable; 我有点习惯在Lua做这样的事
我正在寻找一些简写if / else代码,但不像$var? $a:$b它不需要’else’之类的返回值.我想要的基本上是这个,但更短:
$myVariable = "abc"; echo $myVariable ? $myVariable : "hello"; echo $myVariable ? "hello" : $myVariable; 我有点习惯在Lua做这样的事情,就像: local myVariable = "abc" -- In case myVariable is false,print "hello". Otherwise it prints "abc" print ( myVariable or "hello" ) -- In case myVariable does have something (So,true) print "goodday." print ( myVariable and "goodday" ) 所以我想知道,PHP有功能做这样的事情吗? 解决方法$myVariable ? $myVariable : ""; 相当于: $myVariable ?: ""; PS:你应该知道PHP在这里打字玩杂耍.这基本上与以下相同: if ($myVariable == TRUE) ... 如果$myVariable恰好是一个类似0的字符串,它将评估为false.但是00将评估为真.我发现这不像它看起来那么有用.在许多情况下,您需要检查是否先设置$myVariable,或者进行类型比较并确保变量是布尔值… (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |