5.2 Initialization
Try to initialize local variables while declaring them. The only reason not to do this is if the initial value of the variable depends on some computation that occurred previously.
5.3 Layout
Declare variables only at the beginning of a code block. (A block is any code enclosed between curly braces "{" and "}".) Do not declare a variable the first time it is used. This can confuse programmers who are distracted, and can hinder the portability of code within that scope.
function myMethod() {
int $int1 = 0; // Beginning of method block
if ($condition) {
int $int2 = 0; // Beginning of "if" block
...
}
}
One exception to this rule is the index variable of a for loop
for (int $i = 0; i < $maxLoops; $i++) { ... }
Prevent declared local variables from overwriting variables declared at the previous level. For example, don't declare the same variable name inside an inner code block:
int $count;
...
function myMethod() {
if ($condition) {
int $count = 0; // Avoid this declaration
...
}
...
}