What is the default value of class member variables in PHP?
Why do I often see:
public static $variable = null;
Wouldn't it be enough:
public static $variable;
variable_name − This is the name of variable given by user. value − Any value to initialize the variable. By default, it is zero.
Use member initializers in the same order as their declaration. Member variables are always initialized in the order they are declared in the class definition.
Unlike some programming languages, C/C++ does not initialize most variables to a given value (such as zero) automatically. Thus when a variable is given a memory address to use to store data, the default value of that variable is whatever (garbage) value happens to already be in that memory address!
You can simply provide a default value by writing an initializer after its declaration in the class definition. Both braced and equal initializers are allowed – they are therefore calle brace-or-equal-initializer by the C++ standard: class X { int i = 4; int j {5}; };
Setting it to null
explicitly makes the initial value clear even to people who don't know every intimate detail of PHP.
It would, but some people either don't know that, or prefer to be explicit.
A common convention is to initialize to null when the programmer relies on that null value and do not initialize to null if that member is written to before being read.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With