开发者

PHP: Are these statements equivalent? (file_exists())

Aren't these equivalent?

==SCRIPT A==

if (file_exists($file) == false) {
     return false;
}

==SCRIPT B==

if(!file_exists($file)) {
     r开发者_如何学JAVAeturn false;
}


Plain answer: Y E S

They evaluate to the same thing.

That first one might be even better suited like this:

if (file_exists($file) === false) { // === checks type and value
     return false;
}

OR:

return file_exists($file);


yes, file_exists returns a boolean, so it's either true or false.

so you could return file_exists($file) as well...


If you are making boolean comparisons, then you would rather do this:

if (file_exists($file) === false) {
    return false;
}

using the === operator, to ensure that what you are receiving is a variable of type boolean and of value equivalent to false.


Yes.

But if you would use:

if (file_exists($file) === false) {
    return false;
}

then it would not be the same as:

if(!file_exists($file)) {
    return false;
}

because in the first case it would check whether the value returned by function matches strictly to false, and in the second case the value returned by function would be evaluated to boolean value.

EDIT:

That is general rule.

But in case of file_exists() function, which returns boolean value, evaluating to boolean is not necessary, thus you can use strict condition and this will have the same result (but only in case you know the value will be either true or false.


If you're asking "what's the difference between the === and == operator" then:

'===' is a strict comparison that checks the types of both sides. '==' is an 'equivalent to' comparison operator that will cast either side to the appropriate type if deemed necessary.

To expand, '==' can be used to check for 'falsey' values and '===' can be used to check for exact matches.

if (1 == TRUE) echo 'test';
>> "test"

if (1 === TRUE) echo 'test';
>>

If you're asking if there's any functional / practical difference between your two code blocks then no, there isn't and you should be returning as such: return file_exists($file);

Worth a read: http://php.net/manual/en/language.operators.comparison.php

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜