Rich
Rich

Reputation: 1156

Why have an empty PHP Variable?

I've been reviewing a lot of PHP code lately and I keep coming across situations like this:

function () {

    $var = '';

    if ( ... ) {
      $var = '1';
    }

    echo $var;

}

An empty variable is declared and then later defined.

Is there a reason behind this?

The only reason I can think of for doing this is just to make sure $var starts out as empty in case it's previously defined.

Upvotes: 1

Views: 83

Answers (3)

Chemdream
Chemdream

Reputation: 627

If you did not have the $var = ''; you would then need

if (isset($var)) {
    echo $var;
} else {
    echo '';
}

This really helps when you are returning something like an AJAX call. You can initialize everything to '' or FALSE. This way, javascript won't error because something it is expecting is always there, even if it is FALSE or blank.

Upvotes: 0

Sebas
Sebas

Reputation: 21542

If you don´t define $var and the if condition fails, you get an undefined variable $var, assumed constant var notice. (E_NOTICE)

Upvotes: 5

John Conde
John Conde

Reputation: 219894

If if ( ... ) { evaluates to false $var will never be defined. So when echo $var is executed a NOTICE will be displayed that $var is not defined. By defining a default value you prevent this situation from occurring.

Upvotes: 2

Related Questions