变量前面的感叹号 - 需要澄清 [英] Exclamation mark in front of variable - clarification needed
问题描述
我已经使用PHP了很长一段时间了,但这对我来说总是一个谜,在变量前正确使用感叹号(负号)。
I've been working with PHP for quite a while now, but this was always a mystery to me, the correct use of the exclamation mark (negative sign) in front of variables.
!$ var
表示什么? var false
,为空,未设置等等。
What does !$var
indicate? Is var false
, empty, not set etc.?
以下是我需要学习的一些示例.. 。
Here are some examples that I need to learn...
示例1:
$string = 'hello';
$hello = (!empty($string)) ? $string : '';
if (!$hello)
{
die('Variable hello is empty');
}
这个例子有效吗?如果 $ string
为空,if语句是否真的有效?
Is this example valid? Would the if statement really work if $string
was empty?
示例2:
$int = 5;
$count = (!empty($int)) ? $int : 0;
// Note the positive check here
if ($count)
{
die('Variable count was not empty');
}
此示例是否有效?
我从不使用上述任何一个例子,我将这些 if($ var)
限制为只有布尔值的变量。我只需要知道这些示例是否有效,这样我就可以扩大 if($ var)
语句的使用范围。他们看起来很干净。
I never use any of the above examples, I limit these if ($var)
to variables that have boolean values only. I just need to know if these examples are valid so I can broaden the use of the if ($var)
statements. They look really clean.
谢谢。
推荐答案
if(!$ a)
与相同if($ a == false)
。此外,应该考虑使用 ==
运算符时发生类型转换。
有关详细信息,请查看与...的松散比较==此处部分。从那里开始,字符串0和等于FALSE(0== false
为TRUE且= = false
也是TRUE。
if(! $a)
is the same as if($a == false)
. Also, one should take into account that type conversion takes place when using ==
operator.
For more details, have a look into "Loose comparisons with ==" section here. From there it follows, that for strings "0" and "" are equal to FALSE ( "0"==false
is TRUE and ""==false
is TRUE, too).
关于发布的示例:
示例1
它会起作用,但你应该注意,0和都是'空'字符串。
Regarding posted examples:
Example 1
It will work, but you should note, that both "0" and "" are 'empty' strings.
示例2
它将起作用
Example 2
It will work
这篇关于变量前面的感叹号 - 需要澄清的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!