Enums in PHP5

Posted: September 22nd, 2008 | Author: | Filed under: PHP | Comments Off on Enums in PHP5

Enums are very usefull. Unfortunately php does not natively implement it as a type. Not to worry, there is an easy workaround. To implement a simple status enum having values for “ok”, “not-ok” and “uncertain”, try:

abstract class Status implements Enum {
	const UNCERTAIN = 0; // or any other value you wish
	const OK = 1;
	const NOT_OK = 2;

	public static function values(){
		return new ArrayIterator(array(Status::UNCERTAIN,
			 Status::OK,
			 Status::NOT_OK));
	}
}

The values of the enumeration are now immutable, which makes it preferable to implementing such a construct as an array. The enum interface provides the static values() function that allows the caller to iterate over the values that have been enumerated.

interface Enum {
	/**
	 * Return an array containing the enum values to iterate over
	 * @return Traversable Contains enum values
	 */
	public static function values();
}

And that’s it. To use it, call Status::OK and the right value is used throughout your application. To loop, simply call foreach (Status::values() as $enum_value){...}.

This approach works well when several classes use the same naming for (some of) their properties. When using enums in a database, using this pattern will ensure the correct values are used. Also this will allow easy modification of the values in your app when the values in the database need to be changed.


Benchmarking DOMDocument creation with PHP

Posted: September 19th, 2008 | Author: | Filed under: PHP | Tags: | 2 Comments »

Representing data as XML has several advantages, all of which are not in the scope of this post. We will test several ways of creating a DOMDocument instance with a simple XML document. We will not be discussing differences between DOMDocument or SimpleXML or any of the other ways available to build XML structures. This post is concerned with the building (no manipulation either) of a simple XML tree.

Read the rest of this entry »


Benchmarking call_user_func

Posted: September 19th, 2008 | Author: | Filed under: PHP | Tags: | Comments Off on Benchmarking call_user_func

Calling object methods can be done in several ways:

  1. $oObject->method($param);
  2. $sMethod = 'method'; $oObject->{$sMethod}($param);
  3. call_user_func(array($oObject, 'method'), $param);

(call_user_method() function has been deprecated as of PHP 4.1.0, c.f. php.net.)

Intuitively the first type method calling is the preferred way to go both in terms of perfromance and readability. However, for the sake of generality (freedom, scripting or just exploiting the possibilities php provides), one of the latter two could be preferred. A quick performance comparisson may show which to use.

Read the rest of this entry »