2014-01-24 53 views
0

只是做了一些验证,并希望真正了解这是什么意思,而不是它只是工作。

可以说我有:

$email = $_POST['email']; 
if(!$email) { 
echo 'email empty' 
} 

请告诉我只是有变量,没有检查它=什么意思?

我想

$variable 

通过自身意味着它返回的变量为真。

,所以我也用,如果

!$variable 

是指假的。

只是想清楚使用变量本身背后的实际含义。

比较变量是否为空也是不好的做法吗?

因此,它是更好地使用

$email == '' 

!$email 

很抱歉,如果它没有真正的答案一个小问题需要解决,就像到100%了解我所编码实际上有效。

+2

表达式中使用的任何变量被评估为虚假或真实。 falsy表示空,null,等于0,或为false。真是别的。因此,测试!$ var会测试您认为是错误的所有类型的值。 – njzk2

回答

2

$email = ''将清空变量。您可以改用=====

在这种情况下,最好使用PHP的isset()函数(documentation)。该功能正在测试是否设置了变量而不是NULL

3

PHP使用在http://www.php.net/manual/en/language.types.boolean.php处定义的规则来评估$email是否“真实”。

When converting to boolean, the following values are considered FALSE: 

the boolean FALSE itself 
the integer 0 (zero) 
the float 0.0 (zero) 
the empty string, and the string "0" 
an array with zero elements 
an object with zero member variables (PHP 4 only) 
the special type NULL (including unset variables) 
SimpleXML objects created from empty tags 

PS $email= ''将分配给''$email

1

当你做if(<expression>),它评估<expression>,然后将其转换为布尔值。

docs,它说:

When converting to boolean, the following values are considered FALSE: 

the boolean FALSE itself 
the integer 0 (zero) 
the float 0.0 (zero) 
the empty string, and the string "0" 
an array with zero elements 
an object with zero member variables (PHP 4 only) 
the special type NULL (including unset variables) 
SimpleXML objects created from empty tags 

Every other value is considered TRUE (including any resource). 

所以,当你做if(!$email),将其转换$email到按照上述规则布尔反,然后该布尔值。