PHP has two methods which should work the same way. The and
operator and the &&
operator.
But if you do not pay attention your program will be broken.
<?php
function has_access($type, $id) {
if ($id === 0) return true;
else return false;
}
$article_id = 0;
$uid = 14;
$is_zero = $article_id == 0;
$has_acc = has_access('update', $uid);
$ok = $article_id == 0 && has_access('update', $uid);
$wtf = $article_id == 0 and has_access('update', $uid);
echo "\$article_id == 0 // => ";
var_dump($is_zero);
echo "has_access('update', \$uid) // => ";
var_dump($has_acc);
echo "\n";
echo "\$article_id == 0 && has_access('update', \$uid) // => ";
var_dump($ok);
echo "\$article_id == 0 and has_access('update', \$uid) // => ";
var_dump($wtf);
The optimal output:
$article_id == 0 // => bool(true)
has_access('update', $uid) // => bool(false)
$article_id == 0 && has_access('update', $uid) // => bool(false)
$article_id == 0 and has_access('update', $uid) // => bool(false)
The real output:
$article_id == 0 // => bool(true)
has_access('update', $uid) // => bool(false)
$article_id == 0 && has_access('update', $uid) // => bool(false)
$article_id == 0 and has_access('update', $uid) // => bool(true)
Or a simple question:
<?php $variable = true and false;
What will be the value of $variable
? Just check it with php -a
.
I think it’s a very stupid operation. (see: php.net > Operator Precedence)