php 变量前面的感叹号 - 需要澄清
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13029921/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Exclamation mark in front of variable - clarification needed
提问by aborted
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.
我已经使用 PHP 有一段时间了,但这对我来说一直是个谜,正确使用变量前面的感叹号(负号)。
What does !$varindicate? Is var false, empty, not set etc.?
是什么!$var指示?是 var false、空的、未设置的等吗?
Here are some examples that I need to learn...
这里有一些我需要学习的例子......
Example 1:
示例 1:
$string = 'hello';
$hello = (!empty($string)) ? $string : '';
if (!$hello)
{
die('Variable hello is empty');
}
Is this example valid? Would the if statement really work if $stringwas empty?
这个例子有效吗?if 语句如果$string为空真的有效吗?
Example 2:
示例 2:
$int = 5;
$count = (!empty($int)) ? $int : 0;
// Note the positive check here
if ($count)
{
die('Variable count was not empty');
}
Would this example be valid?
这个例子是否有效?
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 ($var)为仅具有布尔值的变量。我只需要知道这些示例是否有效,以便我可以扩大这些if ($var)语句的使用范围。他们看起来真的很干净。
Thanks.
谢谢。
回答by bhovhannes
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"==falseis TRUE and ""==falseis TRUE, too).
if(! $a)与 相同if($a == false)。此外,应该考虑到使用==运算符时会发生类型转换。
有关更多详细信息,请查看此处的“与 == 的松散比较”部分。从那里可以看出,对于字符串“0”和“”等于 FALSE("0"==false是 TRUE,""==false也是 TRUE)。
Regarding posted examples:
Example 1
It will work, but you should note, that both "0" and "" are 'empty' strings.
关于发布的示例:
示例 1
它将起作用,但您应该注意,“0”和“”都是“空”字符串。
Example 2
It will work
示例 2
它将起作用
回答by Evert
The !negates. true becomes false, and anything that evaluated to false becomes true.
该!则无效。true 变为 false,任何评估为 false 的内容都变为 true。
If you're writing PHP and you don't know all the operators by heart.. you should not write a single line of code until you know them by heart:
如果您正在编写 PHP 并且您不了解所有运算符.. 在您完全了解它们之前,您不应该编写一行代码:
http://php.net/manual/en/language.operators.php
http://php.net/manual/en/language.operators.php
These are absolute basics.
这些是绝对的基础。
回答by William The Dev
It's a boolean tester. Empty or false.
这是一个布尔测试器。空或假。
回答by mensi
It's the notboolean operator, see the PHP manualfor further detail.
它是not布尔运算符,有关详细信息,请参阅PHP 手册。

