Archive for July, 2008

PHP 5.2.x __toString() Support

Monday, July 28th, 2008

Since updating to PHP version 5.2.2 (which has been superseded yet again since this post) the default behavior of class objects is to raise an error when cast to a string (usually a 'Catchable Fatal Error', citing that the object could not be converted to string!).

This is quite irritating, as previously the default behavior would be to return a unique object identifier. However, there is a quick workaround for this problem should your script rely upon object string casting / this unique object identifier.

The Fix

When creating your class, add in __toString() as a function. This so-called 'magic function' is called when trying to cast an object to string, such as (string) $someObject. The following combines this function with a call to spl_object_hash(), which provides an identifier hash for the object:

<?php

class SomeClass {
	function __toString() {
		return spl_object_hash($this);
	}
}

$someObject = new SomeClass;
echo $someObject;

?>

The above code is fairly self-explanatory and it saves you from at least a few of minutes banging your head on the table :-)

Glancing normality

Monday, July 21st, 2008

My recent absence and unfulfilled promise of geeky goodness has not been entirely in vain! For the past month or so I've been wrapped up in academic pursuits - ranging from preparing cell cultures to programming with Cell microprocessors!

As a result, I have a rather large backlog of draft posts that I haven't had the time (read: been bothered) to complete. This week marks the beginning of my Big Blog Catchup - starting with some bits and pieces about running Fedora Core 7 on a Sony PlayStation 3!