note 72532 added to language.oop5.magic
| From: | DéricoFilho at osu1 dot php dot net | Date: | Tue, 23 Jan 2007 15:33:52 +0000 |
| Subject: | note 72532 added to language.oop5.magic | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-122073@lists.php.net to get a copy of this message | ||
Since PHP 5.2.0, you'll always get an error like this:
"Object of class foo could not be converted to string"
When one tries to use an object as string, for instance:
class Test{}
echo new Test();
Thus, one way to avoid this problem is to programme the magic method __toString.
However, in the older versions, it would output a string saying that it was an object together a
unique obj id. Therefore, the __toString() method must comply with this behaviour.
My suggestion:
class Test{
function __toString(){
if(!isset($this->__uniqid))
$this->__uniqid = md5(uniqid(rand(), true));
return(get_class($this)."@".$this->__uniqid);
}
}
echo new Test();
would output something like this:
Test@6006ba04f5569544c10a588b04849cf7
----
Server IP: 200.185.126.100
Probable Submitter: 200.213.210.2 (proxied: 192.168.253.212)
----
Manual Page -- http://www.php.net/manual/en/language.oop5.magic.php
Edit -- https://master.php.net/note/edit/72532
Del: integrated -- https://master.php.net/note/delete/72532/integrated
Del: useless -- https://master.php.net/note/delete/72532/useless
Del: bad code -- https://master.php.net/note/delete/72532/bad+code
Del: spam -- https://master.php.net/note/delete/72532/spam
Del: non-english -- https://master.php.net/note/delete/72532/non-english
Del: in docs -- https://master.php.net/note/delete/72532/in+docs
Del: other reasons-- https://master.php.net/note/delete/72532
Reject -- https://master.php.net/note/reject/72532
Search -- https://master.php.net/manage/user-notes.php