Converting an object to a string

Hi guys!

I’m having problems using an object in a comparison; every type of comparison generates an error:

[error] PHP Catchable fatal error: Object of class stdClass could not be converted to string in ...

I’m building a theme in WordPress, and I’m trying to use the $post->post_name variable.

I’ve tried if and ternary, I’ve tried converting the object with strval() and [URL=“http://us3.php.net/manual/en/function.settype.php”]settype(), I’ve tried passing its value into an array and then imploding the array to get at the string … nothing!

I can echo the object out, but I cannot use it any comparison inside the Loop.

But, bizarrely, even if I perform the conversion outside of the Loop — which works — the moment I use the new string variable — no matter what its name is — back inside the Loop, I get the same error.

This is utterly baffling. I’ve never see anything like this. It’s like it knows what I’m trying to do and it won’t let me! :lol:

Any help would be cool…

why do you want to convert an object to a string and what result do you expect?
Do you really compare objects? Or just a variable member of object?

Create a new class and define the magic __toString method of that class. This function is invoked any time the object is asked for a string representation of itself. Since it’s a function you’ll have full control of what gets output by the class. Further, since you’ve defined the behavior of the object when converted to a string the error will not be raised.

Thanks for your reply, but please read fully my opening post.

Well that’s what I’ve been looking at, but I can’t see why I’ve got to create a class and a method just so I can compare the values of two objects, both of which contain nothing more than string values.

PHP is meant to handle all of this on the fly. Since that’s failed, I’ve tried converting the object and that’s failed too.