Neither PEAR nor we define a clear coding-standard for the logical negation operator ("!" as in !$foo). However, to my knowledge, all of Drupal core + contrib is using:
<?php
if (!$foo) {
bar();
}
$c = !$a;
?>In a code clean-up issue for Better Formats module, dragonwize proposed to use a space between the operator and following code, as we do with the concatenation operator and arithmetic operators:
<?php
if (! $foo) {
bar();
}
$c = ! $a;
?>I am very opposed to that proposal. However, he's right in the fact that we don't have a defined standard for this operator (and possibly also arithmetic operators). And, while investigating this, PHP is using a space on their logical operators handbook page (which could end up in another support request on php.net, webchick ;).
My goal is to enhance/rewrite the "String concatenations" chapter in http://drupal.org/coding-standards to document (at least) the negation operator as well. Ideally, I'd like to add a note about arithmetic operators (+ - * /) in one fell swoop.
For arithmetic operators, we are mainly following PHP's docs and use a space before and after the operator:
<?php
$c = $a + $b;
$c = $a - $b;
$c = $a * $b;
$c = $a / $b;
$c = $a % $b;
?>
Comments
+1
+1 from me
I think the extra space is
I think the extra space is pretty ugly - I prefer if (!$foo) and $c = !$a. I'm also assuming this is purely theoretical, as we all know that "if (!$foo)" should be more clearly replaced with "if (empty($foo))" or "if (!isset($foo))". :)
Confusing
I find the extra space a bit confusing, not to mention it might be pretty tedious to maintain. If you were printing out a negative number, you wouldn't put a space between the minus sign and the number:
<?php$number = -50; // without the space is normal
$number = - 50; // with the space just looks weird
?>
Although - and ! have different functions, the concept is the same.
Agree
+1
I agree. A space between
!and the operand would look ridicules.Furthermore,
!is a unary operator (as-in-1), and if mathematical typography can be of any guidance, there should not be any extra space between the unary operator and the operand.Thomas Barregren – NodeOne
Unary, binary and ternary
In the interest of clarity and stringency, we maybe should use the terms unary (e.g.
!), binary (e.g.&&) and ternary (i.e.? :) operators in this context. Which class of operators (e.g. arithmetical and logical operators) they belong to is of less importance.Thomas Barregren – NodeOne
$foo++ -vs- $foo ++ ¿?
+1 for
<?php
$foo++;
if (!$foo) { ...
$foo = !$foo;
$foo = -50;
$foo = $a + $b;
?>