php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #25122 Control over typecasting objects to strings
Submitted: 2003-08-17 22:17 UTC Modified: 2006-04-03 12:29 UTC
Votes:4
Avg. Score:4.5 ± 0.5
Reproduced:3 of 3 (100.0%)
Same Version:0 (0.0%)
Same OS:1 (33.3%)
From: a at b dot c dot de Assigned:
Status: Closed Package: Feature/Change Request
PHP Version: 5.0.0b1 (beta1) OS: Any
Private report: No CVE-ID: None
 [2003-08-17 22:17 UTC] a at b dot c dot de
Description:
------------
String casting for objects. When used in a string context (a simple
example being "echo $object;") objects are currently cast to the string
"object", which is generally less than helpful.

The enhancement is to allow objects to have a method called, say,
"__string" or something similar that is called on an object whenever it
is used in a situation where a string is expected and returns a string
(or something, like a number, that can be readily cast to a string).

One could, for example, have a complex number class, with properties $r
and $i, with a method like 

function __string()
{
  $s = $this->r;
  if($this->i>=0) $s.='+';
  $s.=$this->i;
  $s.='i';
  return $s;
}


so that one can echo or concatenate complex numbers with impunity.

Many classes already possess "toString()" methods, no doubt in part to
Java's influence. These generally perform the role that I am advocating
for __string(), with the difference being that the latter is implicitly
called whenever necessary. Calling the new method "toString()" could be
hazardous for existing scripts that already use classes with methods
with this name. Backward compatibility can of course be achieved by
writing one of


function __string()
{ return $this->toString();
}

function toString()
{ return $this->__string();
}


which will give the two methods identical behaviour, except of course
for the fact that toString() is an ordinary  method that needs to be
called explicitly.

Not to be confused with the operation of serialize(); __string() is
intended for e.g., human-readable string representations of an object
and isn't necessarily reversible to produce the original object. A
complex hierarchical object might, for example, generate XML as a
result of calling its __string() method; in the example above, a complex
number might have a string string representation of "-12+2.5i";
something containing binary data (e.g., an image) might return a textual
description of the data's contents rather than the data itself.

Needless to say, if the __string() method is absent, casting reverts to
the existing "cast to 'object'" behaviour.



Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2004-04-06 19:36 UTC] bendik at infofab dot no
From the latest change log - 18-Mar-2004

"Changed __toString() to be called automatically only 
with print and echo  statements. (Andi)"

I can not for the life of me figure out why this has 
been done. Why should an object behave differently when 
it is echoed alone and when it is concatinated?
Example:
(the class "Foo" has a __toString() method 
defined.(returns "World"))

$obj = new Foo();

echo $obj; // Produces: World!

echo "Hello, " . $obj; // Produces: Hello, Object id #1

Why, oh why?
 [2004-04-06 21:42 UTC] amt@php.net
This was changed to prevent crashes. This will hopefully 
be fixed in 5.1, but cannot be fixed in time for 5.0. 
Sorry.
 [2004-04-07 03:10 UTC] derick@php.net
It's still an open feature request Adam.
 [2005-09-26 03:34 UTC] a at b dot c dot de
Is this still open?

One method that (from this angle) appears quite elegant would be to give stdClass a __toString() method that simply returns "Object" (or even "Object" and an ID#, a la resources). Then any other __toString() methods in any other classes would simply be overriding this one.

The clear advantage this gives is that __toString() can be then called with impunity on any object, safe in the knowledge that it exists. The type casting engine already knows how to cast objects to arrays; if it needs to cast the object to anything else it can hapily call __toString() and proceed from there.

The obvious issue hinted at in the previous paragraph is that the entity that the object is cast to may require further casting in order to fit in with whatever expression is being evaluated at the time. This is something that may happen anyway: without rigorously type-checking (at runtime) the value returned by __toString() to ensure that it really is a string, it has to be assumed that the method could return anything, ranging from Void to Null to Object. And it's all too reasonable to expect that method writers will want to return, say, integers in the expectation that they will be cast to strings as per normal. So after an object has been cast into the result of its __toString() method, that result would need to be checked again, and, if necessary, recast again. And it's the method writer's own silly fault if PHP hangs when they write something that boils down to "function __toString(){return $this;}".
 [2006-04-03 12:29 UTC] tony2001@php.net
Already implemented.
 
PHP Copyright © 2001-2024 The PHP Group
All rights reserved.
Last updated: Wed Sep 18 19:01:28 2024 UTC