Posts Tagged ‘toString’

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 :-)