Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default value of member variables

Tags:

oop

php

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;
like image 825
takeshin Avatar asked Jun 21 '10 22:06

takeshin


People also ask

What is the default value of a variable?

variable_name − This is the name of variable given by user. value − Any value to initialize the variable. By default, it is zero.

Are member variables default initialized C++?

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.

What is the default value of a variable in C++?

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!

How can we provide a default value for a member of a class?

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}; };


2 Answers

Setting it to null explicitly makes the initial value clear even to people who don't know every intimate detail of PHP.

like image 38
Joey Avatar answered Oct 03 '22 03:10

Joey


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.

like image 105
Artefacto Avatar answered Oct 03 '22 03:10

Artefacto