Mathematics, philosophy, programming, in-line skating and everything in between. More about me…

My Blog

My Latest Tweets

Follow me on Twitter…
English | Czech
Choose your language. I write in English, but I translate most of my articles to Czech as well. Zvolte si jazyk. Píšu anglicky, ale většinu svých článků překládám i do češtiny.

Simple Object Improvement in PHP5

PHP has many unpleasant features. One of them is a certain inconsistency when handling object properties and object methods. When you try to use a nonexistent method, PHP throws a fatal error and stops the execution. However, access to an undefined property results in a mere notice. There is a primitive way to remedy this, however. We can replace the notice by a nice, juicy fatal error.

We can make use of the specific property overloading in PHP5. When you try to read a nonexistent property, PHP5 first checks whether your object has the magic __get() method. If so, no notice is emitted and you can take care of the business yourself. Writing to nonexistent properties can be handled by __set() it the same way. See the relevant section of the PHP manual for a more detailed description.

The idea is straightforward: a call to __get() or __set() tells us that PHP was about to emit a notice about an unknown property. All we need to do is to start complaining instead of PHP :-). So, let’s create a base class that will implement the two magic methods:

<?php
abstract class Object {
	public function __get($var) {
		trigger_error('Undefined property: ' . get_class($this) . '::$' . $var, E_USER_ERROR);
	}

	public function __set($var, $value) {
		trigger_error('Undefined property: ' . get_class($this) . '::$' . $var, E_USER_ERROR);
	}
}

All classes will then be derived from the base class. A simple test case:

<?php
class A extends Object {
	public
		$lorem,
		$ipsum,
		$dolor,
		$sit;
}

$a = new A();
$a->lorem = 1;
echo $a->amet; // Fatal error: Undefined property: A::$amet in (file) on line (line)

It is possible, of course, to replace the errors by exceptions or to change the error severity. To each their own.

September 1, MMVIII — PHP and Programming.

Speak your mind

Allowed HTML tags are a, blockquote, em, code, li, ol, p, pre, strong, ul. Links to other comments in the form “[IV]” or “[4]” are detected automatically.