Jump to content

__toString() doesn't return my string


Jessica

Recommended Posts

I am trying to use the PHP5 magic function __toString() (Doc: http://us2.php.net/manual/en/language.oop5.magic.php) in some of my classes, and it isn't returning what I specify, it returns the object ID number.

 

Here's what I have:

Class Attribute{
var $attributeID;
var $attribute;

function __toString(){
	return $this->attribute;
}
}

 

Now, when I try to use it here, when $atts is an array of Attributes()

if(count($atts)){
foreach($atts AS $v){
	print $v.'<br />';
}
}

I get stuff that looks like this:

Object id #4

Object id #7

 

But if I do

print $v->attribute.'<br />';

 

It shows up properly as

Color

Size

 

So, what's the dilly-yo? I made sure it's running PHP5, but even if it were PHP4 it should still work when I do the print, yeah?

Link to comment
Share on other sites

What I ended up doing is changing the point of my function so instead of returning a string which I could print later, it just prints the values itself.

What I had was:

if(count($atts)){
$str = '';
foreach($atts AS $v){
	$str .= $v. '<br />';
}
return $str;
}

 

Change to:

if(count($atts)){
foreach($atts AS $v){
	print $v;
	print '<br />';
}
}

 

I tried typecasting with (string), using {} syntax, everything I could think of. :( If anyone ever figures out a way to do this...post!

Link to comment
Share on other sites

Gah, sorry to bump again, just wanted to add this:

What I NOW have done is just use the $a->attribute since it was just one value. The __toString() would be valuable here if I were returning more, such as all of the variables concatenated. However, in this case it's a bit of overkill for what I was trying to do.

Link to comment
Share on other sites

From what I recall I read, there was a lot of disagreement of when toString() would convert or not, I figure this is one of those quirks the function has.

 

a simple workaround would be instead of doing

 

print $v . '<br />';

 

you could do

 

print $v , '<br />';

 

since echo and print can actually print comma separated values as well.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.