note 108751 deleted from language.variables by danbrown
| From: | danbrown@php.net | Date: | Wed, 23 May 2012 03:49:31 +0000 |
| Subject: | note 108751 deleted from language.variables by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-188145@lists.php.net to get a copy of this message | ||
Note Submitter: Jeffrey
----
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.