1

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.

2
  • 3
    It's a preset in this very case, because the second assignment is conditional. $var would else resolve to NULL; with a Notice (which this approach is often used for to eschew). Commented Aug 31, 2014 at 2:24
  • Try to put "@" before the variable at echo. echo @$var; this will by pass the E_NOTICE Commented Sep 6, 2014 at 15:45

3 Answers 3

5

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

Sign up to request clarification or add additional context in comments.

1 Comment

Not exactly an Error, just a Notice. Still should be avoided. Besides, attempting to obtain the value of an undefined variable will get you null, not an empty string. This can be relevant depending on what you are doing.
2

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.