Attached is a fairly simple (and rough) patch that adds support for a
"special" __string() object method to ZE2. I wrote it for fun, but I
thought there might be general interest in the idea, so I'm posting it
here. The idea is inspired by Python's str method [1].
Here's how it works in practice:
class Foo { }
class Stringy extends Foo
{
function __string()
{
return 'blah';
}
}
$foo = new Foo();
$stringy = new Stringy();
print "$foo\n";
print "$stringy\n";
$a = (string)$foo;
$b = (string)$stringy;
print "$a\n";
print "$b\n";
Output:
Object id #1
blah
Object id #136238812
blah
So, essentially, if an object offers a __string() method, it will be
used whenever a string representation of the object is requested. I
can see this being useful for things like object serialization or as a
shortcut for things like the Exception class's toString() method.
The patch is attached. Comments are welcome.
[1] http://www.python.org/doc/current/ref/customization.html
--
Jon Parise (jon@php.net) :: The PHP Project (http://www.php.net/)