PHP - not operator, any other aliases?
if(!($whatever && what()) do_stuff...
Can this be replaced with something more intuitive like:
if(n开发者_如何学Pythonot($whatever && what()) do_stuff...
?
function not($OriginalCheck)
{
return !$OriginalCheck;
}
function is($OriginalCheck)
{
return !!$OriginalCheck;
}
should do exactly that :)
There are several ways to write checks:
if(!($whatever && what()) do_stuff...
if(!$whatever || !what()) do_stuff...
if(($whatever && what()) === false) do_stuff...
if((!$whatever || !what()) === true) do_stuff...
if($whatever === false || what() === false) === true) do_stuff...
all these ways are intuitive and known through out the programming world.
No it can't. See http://www.php.net/manual/en/language.operators.logical.php for the language reference about logical operators, and navigate to find other aliases.
Note however that the precedence of &&
and ||
is not the same as and
and or
.
One option is to make the boolean expression more explicit:
if(($whatever && what()) == false) // do_stuff...
Or alternatively, by implementing a custom not()
:
function not($expr) {
return $expr == false;
}
if(not($whatever && what())) // do_stuff...
Actually, I don't like the !
operator as well. Although it was understood by every developers but it took me a bit of time every time I read the code. So I prefer do not use the !
operator. But it depends on also.
For php built-in function, I created almost the helper functions for not operator.
https://github.com/vuvanly/not-operators-helpers
There is no alternative !
, but it could be written less intuitive:
if ($whatever - 1) {
}
Should the question cause be that !
is too easy to overlook, but not
more visible; then another alternative notation would be:
if (!!! $whatever) {
If this still looks to simple, just use:
if (~$whatever & 1) {
Binary operations always look professional ;)
精彩评论