In my opinion, sample #2 seems to be the more readable way of commenting.
But if I apply PSR-2 to both samples, sample #1 won't change but the result of sample #2 changes as below and it's not a proper comment.
What is the best way to comment in these case?
sample #1/* Read cached data */
if ($useCache == true){
// do something
/* Download and cache data */
} else {
// do something
}
sample #2
/* Read cached data */
if ($useCache == true){
// do something
}
/* Download and cache data */
else {
// do something
}
PSR-2 result of sample #2
/* Read cached data */
if ($useCache == true){
// do something
} /* Download and cache data */
else {
// do something
}
So far the best way seems to be as below: Marking them inside the brackets
if ($useCache == true){
/* Read cached data */
// do something
}
else {
/* Download and cache data */
// do something
}
PSR-2 doesn't address how to make comments or block comments on purpose, so you can do as you please.
There are many elements of style and practice intentionally omitted by this guide. These include but are not limited to:
- Declaration of global variables and global constants
- Declaration of functions Operators and assignment
- Inter-line alignment
- Comments and documentation blocks
- Class name prefixes and suffixes
Ref : http://www.php-fig.org/psr/psr-2/#conclusion
However, acording to PSR-2, the opening brace should be separated from the if()
condition by a space character, and the else
should be on the same line and next to the preceding closing brace, like so :
<?php
if ($expr1) {
// if body
} elseif ($expr2) {
// elseif body
} else {
// else body;
}
Ref: http://www.php-fig.org/psr/psr-2/#51-if-elseif-else
Imho, your comment being relative to what is done inside the else
block is a pretty good reason why it should be placed inside that block (only functions, classes and top-level constructs have the privilege to have a docblock extracted above them), so I tend to agree with Ibu's comment in that respect (If you were to edit or delete the else block at some point, the block comment should be updated as well).