) usage in a return command
I've come across some interesting usage of the || operator in a return command, and would appreciate it if someone could confirm exactly what is going on (if I understand it, I can use it myself in the future)
The code is
return ( empty($neededRole) || strcasecmp($role, 'admin') == 0 || strcasecmp($role, $neededRole) == 0 );
$neededRole and $role are either null, 'admin' or 'manager'
I'm reading it as:
If $neededRole
is empty, no further checks are needed. Return true (and stop checking)
If ($role == 'admin')
then allow access, no matter the required role. Return true (and stop checking)
if ($role == $neededRole)
then allow access. Return true (and stop checking)
I'm guessing that upon reaching a 'true' that the checking stops, and if it reached the end of the line without having a 'true', it will default to false.
Am I close to the mark?
Yes, you are correct. This is called short-circuit evaluation. The final return value if all the conditions evaluate to false will be false || false || false
false || false || false
false || false || false
which is false.
As a side note this also works with the &&
operator, but it stops evaluation when the first expression results in a false
value.
Yes, you are right
See an example in manual
// foo() will never get called as those operators are short-circuit
$a = (false && foo());
$b = (true || foo());
$c = (false and foo());
$d = (true or foo());
链接地址: http://www.djcxy.com/p/10088.html
上一篇: ===在php中是什么意思
下一篇: )在返回命令中的用法