note 108751 added to language.variables

From: Date: Wed, 23 May 2012 03:43:15 +0000
Subject: note 108751 added to language.variables
Groups: php.notes 
Request: Send a blank email to php-notes+get-188144@lists.php.net to get a copy of this message
james at custom-made-sites -- Catchable fatal error: Object of class 'XXXX' could not be converted to string. That's because the class definition did not include a __toString() function. PHP looks for this function when a variable of type object (a compound type in PHP) is ready to be printed. And what makes it worse is that there are probably alot of Class Definitions out there that do not have them. Here's a function -- getClassString() -- to address this social disease. It should be self explanatory. <?php class MyClass1 { } class MyClass2 { public $value1 = 1.025; public $value2 = 24.54; public function __toString() { return "MyClass2 [value1=$this->value1, value2=$this->value2]"; } } function getClassString($classInstance) { $classString = 'Not an object.'; if(is_object($classInstance)) { $classString = get_class($classInstance); $methods = get_class_methods($classInstance); foreach($methods AS $method) { if($method == '__toString') { $classString = $classInstance->__toString(); break; } } } return $classString; } ?> Ok, I've written a couple of class definitions (MyClass1 and MyClass2), and the getClassString() function to fix the problem. Let's do this! <?php $mc1 = new MyClass1(); $mc2 = new MyClass2(); echo getClassString($mc1) . '<br>'; // 'MyClass1' echo getClassString($mc2) . '<br>'; // 'MyClass2 [value1=1.025, value2=24.54]' echo getClassString(255) . '<br>'; // 'Not an object.' ?> Note: Always include a __toString() function in your class definitions -- in my opinion, they rank just as high as the __construct() function if not higher. ---- Server IP: 69.147.83.197 Probable Submitter: 69.19.176.225 ---- Manual Page -- http://www.php.net/manual/en/language.variables.php Edit -- https://master.php.net/note/edit/108751 Del: integrated -- https://master.php.net/note/delete/108751/integrated Del: useless -- https://master.php.net/note/delete/108751/useless Del: bad code -- https://master.php.net/note/delete/108751/bad+code Del: spam -- https://master.php.net/note/delete/108751/spam Del: non-english -- https://master.php.net/note/delete/108751/non-english Del: in docs -- https://master.php.net/note/delete/108751/in+docs Del: other reasons-- https://master.php.net/note/delete/108751 Reject -- https://master.php.net/note/reject/108751 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#188144) next »