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.
var_dump(null === null); // bool(true)
var_dump(null == 0); // bool(true)
var_dump(null == false); // bool(true)
Uninitialised variables are, by default, null
Consider the following code:
class Employee {
protected $salary;
public function __construct() { $this->salary = null;
}
}
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