Possible Du开发者_如何学运维plicate:
PHP ToString() equivalent
I get this error:
Catchable fatal error: Object of class stdClass could not be converted to string
So, my question is, how do I convert an object to a string in PHP? I don't want to serialize it though.
Just a note: the code I use works in PHP 4, but not in PHP 5
Thanks!
EDIT: I resolved it myself. It was a pain, but I did it. Thanks anyway, everyone :-)
Why do you need this string? If you just need to visualize it for debugging, you can use var_dump()
, print_r()
, or $s = print_r($var, 1);
to really make it into a string for further theming. If you need to send the object as text to somewhere else (database, Javascript code), you have a choice of serialize, json_encode, XML conversion, and many more, depending on your exact situation.
You want to convert a PHP object to a string?
if neither var_dump, print_r, var_export, serialize, json_encode nor __toString is exactly what you're after maybe this can help you satisfy your needs.
For PHP 5.3 and above
<?php
$v = (object) array('a' => 1, 'b' => 2, 'c' => 3);
$r = new ReflectionObject($v);
echo $r->getName() .' {' . implode(', ', array_map(
function($p) use ($v) {
$p->setAccessible(true);
return $p->getName() .': '. $p->getValue($v);
}, $r->getProperties())) .'}';
Will output:
stdClass {a: 1, b: 2, c: 3}
For a more conventional approach compatible with previous PHP 5 flavours try
<?php
class ExampleClass {
private $pvt = 'private';
protected $prot = 'protected';
public $pub = 'public';
}
$v = new ExampleClass();
$r = new ReflectionObject($v);
echo $r->getName() ." {\n";
foreach ($r->getProperties() as $p)
if ($p->isPublic())
echo "\tpublic ".$p->getName().': '.$p->getValue($v)."\n";
else
echo "\t".($p->isPrivate()?'private ':'protected ').$p->getName().",\n";
echo "}\n";
Which will print:
ExampleClass {
private pvt,
protected prot,
public pub: public
}
What you need is to add the magic method __toString
to your class so you can print what you want.
Edit: Sorry, just saw "PHP 4, but not in PHP 5".
you can use php magic method __toString
I suspect that this is not a problem with the object not convertable to a string.
It's more like that you are assuming that a variable contains a string, (or something that can represented as a string), but it contains an object, and you are trying to echo that out.
You do not try to convert this Object in string,it will not work. Just fetch exact value from that Object.
As a example if you got output as cost.this cost output is Object. so fetch exact value from this as follows
$var=cost->Postage_cost;
$var1=cost->other_cost;
from the error you get I assume you used the object as a parameter to a function that expects a string. the question is, why you did that and what you expect that function to with the object. and then before passing it to the function, extract a sensible string value.
精彩评论