[英]What is the difference between isset($var) == “Test” and isset($var) && $var == 'Test"
isset($var) == "Test"
和isset($var) && $var == 'Test"
什么区别?
The first one makes no sense. 第一个没有道理。 As you can see
isset
returns a Boolean. 如您所见,
isset
返回一个布尔值。 So isset($var) == "Test"
as I said evaluates a bool against a string. 所以
isset($var) == "Test"
正如我所说的针对字符串评估布尔值。
With the evaluation isset($var) && $var == 'Test'
PHP first checks if the variable $var is defined and then if that value is equal to the string 'test'. 通过评估
isset($var) && $var == 'Test'
PHP首先检查是否定义了变量$ var,然后检查该值是否等于字符串'test'。
Calling just $var == 'Test
without ensuring that it is set will result in an 'Undefined variable' notice. 仅调用
$var == 'Test
如果不确保已设置它,将导致出现'Undefined variable'的提示。 If you are not sure and don't want a noisy log then you can check with isset. 如果您不确定并且不希望出现噪音日志,则可以使用isset进行检查。
Here a short example: 这是一个简短的例子:
$var = "Chuck Test";
var_dump(isset($var)); // bool(true)
var_dump(isset($undefined)); // bool(false)
var_dump(isset($var) == "Chuck Test"); // bool(true)
var_dump(isset($var) && $var == "Chuck Test"); // bool(true)
var_dump(isset($undefined) == "Chuck Test"); // bool(false)
var_dump(isset($undefined) && $undefined == "Chuck Test"); // bool(false)
it looks like they are equivalent but they aren't: 看起来它们是等效的,但它们不是:
var_dump(isset($var) == "Chuck Testa"); // bool(true) !!!
var_dump(isset($var) && $var == "Chuck Testa"); // bool(false)
because isset() returns true
or false
, and an non-empty string compared to true
results in true
. 因为isset()返回
true
或false
,并且将非空字符串与true
进行比较将得出true
。
So better use the isset($var) && $var == "Test"
variant, because it does what you would expect. 因此最好使用
isset($var) && $var == "Test"
变体,因为它可以实现您的期望。
The function isset()
returns true (boolean) if a variable is set. 如果设置了变量,则函数
isset()
返回true(布尔值)。 Now when you compare a boolean == "Test", it is bogus. 现在,当您比较布尔值==“ Test”时,它是假的。 So to check whether your variable is set and has the value of 'Test' you should use
isset($var) && $var == 'Test'
. 因此,要检查变量是否已设置并具有'Test'的值,应使用
isset($var) && $var == 'Test'
。 But I don't see why you should not do `$var == 'Test'. 但是我不明白为什么你不应该做$ var =='Test'。 Does the interpreter complain about uninitialized variable that way?
解释器会这样抱怨未初始化的变量吗?
Read the following, ask any question if you do not understand what the function isset
actually does: http://php.net/manual/en/function.isset.php 阅读下面的内容,问任何问题,如果你有什么不明白的功能
isset
实际上做: http://php.net/manual/en/function.isset.php
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.