PHP Coding Standards – Default Value Variable: Null vs Empty String vs False

clean codecoding-standardsPHP

I would like to initialize my variables at the top of my file, to prevent any Undefined variable notices. But what do you guys think is considered to be best practice (in PHP), in case of a string type variable?

Initialize the variable with a value false by default?

$variable = false;

Or perhaps just an empty string

$variable = '';

Or even a null value

$variable = null;

Best Answer

If you don't have a sensible value to initialize your variable with, then you should not be creating that variable at that point in your code.

If you are getting notices that you are using an undefined variable, then that is a clear indication that you have a problem in your program flow. The correct course of action here is to give those variable a sensible value before they are being used. If such a sensible value doesn't exist, then you need to ask yourself why the variable is being used in the first place.

Just blindly masking Undefined variable notices is not going to make the real problem go away. The Undefined variable notice is only a side-effect of that real problem.