PHP 三元 !empty 而不是计算结果为 true 或 false
是否可以使用速记三元来检查变量是否已设置,而不是评估是否为零或非零?
例如,我尝试过:
$var = 0;
echo (string) $var ?: (string) false ?: 2;
但由于前两个表达式的计算结果均为“0”或“假”,因此显示 2。
我认为也许将它们转换为字符串会产生不同的结果,但事实并非如此。我想零就是零。
我想在分配变量时使用这种风格,例如
$get->var = $get->var ?: $setindb ?: $default;
我想将 $get->var 分配给 $get->var (如果已设置),否则,检查数据库是否有值,否则,使用默认值。
编辑
我想我会提到我知道我可以做类似的事情
$get->var = (!empty($get->var)) ? $get->var : ( (!empty($setindb)) ? $setindb : $default )
但是你可以判断哪个更简单:)
Is it possible to use the shorthand ternary to check whether a variable is set or not instead of whether is evaluates to zero or non-zero?
For example, I tried:
$var = 0;
echo (string) $var ?: (string) false ?: 2;
But since both the first two expressions evaluate to "0" or "false", 2 is displayed.
I thought that perhaps casting them to a string would produce different results, but it did not. Zero is zero I suppose.
I'm wanting to use this style when assigning variables such as
$get->var = $get->var ?: $setindb ?: $default;
I want to assign $get->var to $get->var if it is set, otherwise, check if the db has a value, otherwise, use a default.
Edit
I thought I would mention that I know I could do something like
$get->var = (!empty($get->var)) ? $get->var : ( (!empty($setindb)) ? $setindb : $default )
But you be the judge at which is simpler :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
字符串“0”和“false”被视为
FALSE
-y (假值列表) 值。对于已设置的变量,
isset()
返回TRUE
,而不是NULL
。empty()
将检查变量是否已设置且不是FALSE
值。因此,对于“0”,它将返回TRUE
。我认为您想要的是第三个代码片段,但使用
isset()
,而不是empty()
。最简单的方法(使用最少的括号)是:
由于速记十进制返回第一个参数,因此您不能使用它,因为那将是一个布尔值。 (
isset($get->var) ?: $default
将返回TRUE
、FALSE
或$default
,但从来没有$get->var
的值)编辑:也许您想要类似合并函数的东西?据我所知,PHP 本身并没有提供它,但创建起来很简单。请注意,这可能有点难看,因为它使用传递对函数的引用。我对对此的评论很感兴趣(它像我想象的那么糟糕吗?)。
以上我没有测试过。将数组中的变量作为引用传递(
&
符号)。我很确定它会被诸如coalesce(array(1,"a_string",false));
这样的东西噎住。The string "0" and "false" are considered
FALSE
-y (list of false values) values in PHP.isset()
returnsTRUE
for variables that are set and notNULL
.empty()
will check that the variable is set and that is isn't aFALSE
value. So it would returnTRUE
for "0".I think that what you want is your third code snippet, but with
isset()
, rather thanempty()
.The easiest way to do (with the least amount of brackets) that would be:
Since the shorthand tenary returns the first parameter, you can't use it, because that would be a boolean. (
isset($get->var) ?: $default
would returnTRUE
,FALSE
or$default
, but never$get->var
's value. )Edit: Perhaps you'd like something like a coalesce function? PHP doesn't offer it natively, as far as I know, but it's trivial to create. Note that this might be a bit ugly, due to its use of passing references to a function. I'd be interested in comments on this (is it as bad as I think it is?).
I haven't tested the above. Pass variables in the array as references (
&
symbol). I'm pretty sure it'll choke on something likecoalesce(array(1,"a_string",false));
.