Nope, absolutely not. In fact, if I were to come across the snippet you posted, I'd probably replace it with:
echo 'hello';
Because (some PHP internals stuff):
$output = '';
initializes a new PHP value (zval
), sets it to type string, sets the length to 0, and alloates memory for an empty C string (1 byte: {'\0'}
). Then:
$output = 'hello';
Does the exact same thing, but decrements the reference count for the zval you've just created. Its' now not referenced anywhere, and the allocated memory will be freed. This is pointless overhead.
echo $output;
Is fine, it just passes the second zval you've created to the echo construct. But why assign it to a variable in the first place? Why not simply pass the string directly by writing echo 'hello';
?
So when should you declare variables up front:
- When you're concatenating strings in a loop
- When you're using an operator + assignment shorthand in an expression (
*=
, ++
, |=
, ...)
- When the variables are properties
- When your assigning variables in a conditional statement, and use it later on (the variable might not be declared then).
Some examples, starting with concatenation:
$string = '';
foreach ($arr as $k => $v) {
//concatenate
$string .= $k . ' => ' . $v;
}
Shorthand stuff:
$doesNotExist += 123;//evaluates to null + 123 => 0 + 123
$newVar++;//is the same as $newVar = null + 1;
This issues a notice (because $doesNotExist
doesn't exist of course). You can do this, but only after making sure the variables you use in expressions like these actually exist:
//$i is initialized, ++$i is safe here
for ($i=0;$i<10;++$i)
echo $i;
function doubleInt($x)
{
$x *= 2;//safe, $x is argument, so will exist
echo $x;//use the variable safely
return $x;
}
Next properties (more details on why predeclared properties are faster can be found here)
class Foo
{
/**
* @var int
*/
protected $foo = 0;
/**
* @var array
*/
public $bar = [];
}
predeclared variables are marginally faster, you can define the visibility of them, and they stop you from relying on public variables added on the fly (overloaded properties, as PHP calls them). It makes your code easier to understand/maintain/test and less error prone, especially if you don't allow dynamic properties to be added by implementing a __set
method:
public function __set($name, $val)
{
throw new \RuntimeException(
sprintf(
'%s does not have a property %s',
__CLASS__,
$name
)
);
}
Lastly, this is mainly because most IDE's don't handle these scenario's well:
//some code
if ($someVar === true) {
$newVar = 123;
}
//more code
$x *= $newVar;//if $someVar !== true, $newVar is null here
In these cases, it's better to write:
$newVar = 1;//default value
if ($someVar === true) {
$newVar = 123;
}