Out of the corner of my eye

Non Sibi, Sed Omnibus

Out of the corner of my eye header image 2

PHP: Overloaded member initialisation can be harmful

February 21st, 2008 · No Comments

You know how you can sometimes accidentally “hide” methods in C++ if you don’t overload them in the same way and it can cause lots of pain?

PHP has something even worse…

class Dog
{
protected $voice = 'Woof';

function Bark() { echo $voice; }
}

class Chihuahua extends Dog
{
protected $voice = 'Yip yip yip!';
}

$d1 = new Dog();

$d1->Bark();

$d2 = new Chihuahua();

$d2->Bark();

Outputs:

Woof

Yip yip yip!

…But be careful with those data access levels! If $voice is declared private in Dog, the declaration in Chihuahua is “hidden”, presumably because php fails to assign it because it’s private. You’d think you’d at least get a warning, but no… you just get two woofs. :( One of those “shoot yourself in the foot” features that every language has…

Tags: Web dev