Everything you need to know about working with null in PHP

Admittedly not the most intriguing topic, but understanding null in PHP is essential. Here are a few tips I’ve picked up over the years.

Null is equal to itself

Those of us used to working with relational databases will know that null is a special value not equal to anything else: not even itself. In PHP this isn’t the case. null is actually equal to itself, and, when performing loose comparison, a load of other values as well.

  1. var_dump(null === null); // bool(true)
  2. var_dump(null == 0);     // bool(true)
  3. var_dump(null == false); // bool(true)

Uninitialised variables are, by default, null

Consider the following code:

  1. class Employee {
  2.  
  3.     protected $salary;
  4.  
  5.     public function __construct() {
  6.         $this->salary = null;
  7.     }
  8.  
  9. }

I’ve seen the above (or very similar) enough times to have lost count. The assignment of null to Employee::$salary in the class constructor is unnecessary as it will already be null, having not had a value assigned to it yet. So don’t waste your time ‘initialising’ variables or properties in this way.

Continue reading ›

30 January 2012·No comments·Posted in Code