All in the <head> – Ponderings and code by Drew McLellan –

PHP class properties

PHP has a pretty basic class model. You can define classes and create methods as functions within the class. You can also define properties (aka attributes), although in a fairly loose and seemingly uncontrolled way. Users can instantiate the class and then get and set the properties as they wish.

However, I just read that it’s bad form to let users read and write to properties directly, as this should always been done through a method. That is to say rather than saying $myClass->email=‘admin@example.com’; you should more properly do something akin to $myClass->setEmail(‘admin@example.com’);.

I guess that’s a sensible idea as PHP provides no inherent mechanisms for marshaling values in and out of the properties without resorting to using methods. It does nevertheless seem a little cumbersome to have to create a get and set method for every property. Blurgh.

Something else that’s getting on my tits today is the inability to directly set a property as the default value for an method attribute. That is to say, you can’t do this:

function sendEmail($email = $this->email){ // foo;
}

Instead, you have to something ugly like this:

function sendEmail($email = ‘’){ if (!$email){ $email = $this->email; }
}

This is less than ideal, and although it hasn’t quite spoiled my afternoon, it did make me growl at the wall for a bit. Ho hum. I’m sure it’s all positive really.