Northborn Design Northborn Design - 5 months ago 16
PHP Question

Initializing properties in PHP

While I'm led to believe its likely just a design choice, is there any advantage to initializing properties in PHP to an explicit


As a force of habit I find myself doing:

// ...
protected $_foo = null;
protected $_bar = null;
protected $_baz = null;
// ...

Of course, under circumstances where actual data is intended to be present at object instantiation, there is purpose:

// ...
protected $_array = array('a', 'b', 'c');
protected $_boolean = true;
// ...

Is omission of a
initialization value completely functionally equivalent to inclusion of a
initialization? Are there any other caveats? Also, unless a property is type-checked before any assignments would be made, initialization to an empty array seems like similar situation (and I find myself doing that constantly)



protected $_foo = null;
protected $_foo;

are completely equivalents.
As for me great choise is

  • initialize clearly by null, if it will null by default
  • don't initialize, if it will be overriden in constructor

It helps you to see default values quickly, helps code be self-documenting

Don't initialize array by array() seems to be bad idea because you can't use some function (ex. array_push, array_map)