-2

As the title says, simple example follows. I know the first line is not required, but I have seen that all the time. What is the reason?

$output = ''; // is this line necessary?
if ($xyz) {
    $output = 'hello'; // real value here.
    echo $output;
}

A proper example from WordPress code reference.

https://developer.wordpress.org/reference/functions/adjacent_image_link/

Stickers
  • 75,527
  • 23
  • 147
  • 186
  • 1
    `echo $output = "hello";` Why don't you try it out yourself?! (Short answer: not necessary) – Rizier123 Nov 23 '15 at 16:49
  • Not in the case of the code you've posted: assigning a value to a variable is assigning a value to a variable, whether that value is `''` or whether it's `'hello'`. Why do you think it might be? – Mark Baker Nov 23 '15 at 16:50
  • In the case of your link; unless you assign something to $output outside the loop, then if $attachments is empty it won't be populated by anything inside the loop, so won't exist when it's later needed in the call to apply filters – Mark Baker Nov 23 '15 at 16:52

2 Answers2

2

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;
}
Community
  • 1
  • 1
Elias Van Ootegem
  • 74,482
  • 9
  • 111
  • 149
1

If value is certain to exist, then it is not required. One case where you would want to do that would be as follows:

function get_code ($x, $y)
{
    if ($x === $y) {
        $z = true;
    }

    return $z;
}

This is a trap quite a few people (myself included) fall into. On less strict configurations of PHP, this would not throw a notice, however on stricter settings it would.

function get_code ($x, $y)
{
    $z = false;

    if ($x === $y) {
        $z = true;
    }

    return $z;
}

It is much safer to initialize variables you are going to use later, but are unsure if they will be changed before then.

Flosculus
  • 6,880
  • 3
  • 18
  • 42
  • 1
    PHP won't throw an error when it encounters the code you posted, but it'll issue a notice (undefined variable $z). This is of course to be avoided, but it will initialize a new zval, and set it to `null` – Elias Van Ootegem Nov 23 '15 at 17:05
  • @EliasVanOotegem This is true, still.. purge those notices! – Flosculus Nov 23 '15 at 17:06
  • Of course, `E_STRICT|E_ALL` all the way :) notices mean there's something wrong. I know it's pedantic, but I thought I'd point out the difference between notice vs fatal error vs exception ;) – Elias Van Ootegem Nov 23 '15 at 17:08