469,360 Members | 1,775 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,360 developers. It's quick & easy.

toString() in PHP

Dheeraj Joshi
1,123 Expert 1GB
I was wondering, is there any method as toString() to convert a object to string?

As in JAVA???

Regards
Dheeraj
Jul 22 '09 #1
6 16792
Markus
6,050 Expert 4TB
@dheerajjoshim
PHP has the magic-method __toString(), that can be used to present a textual representation of the object.

Expand|Select|Wrap|Line Numbers
  1. class toString {
  2.     public function __toString() {
  3.         return "Object toString";
  4.     }
  5. }
  6.  
  7.  
  8. $ts = new toString;
  9. printf("toString::__toString() - %s", $ts);
  10. // echo
  11. echo $ts;
  12.  
Jul 22 '09 #2
Dheeraj Joshi
1,123 Expert 1GB
Expand|Select|Wrap|Line Numbers
  1. <?php
  2. class Style {
  3.  
  4.     var $text;
  5. function Style ($text="#000000",)
  6. {
  7.  $this->text=$text;
  8. }
  9. }
  10. ?>
  11.  
  12. <?php $Basic = new Style; ?>
Now i want to convert this object to String

$Basic::__tostring();
Wont work..


Any suggetions?
Jul 22 '09 #3
Markus
6,050 Expert 4TB
Your class must implement the __toString() method - you don't call it yourself. Look again at my example.
Jul 22 '09 #4
Dheeraj Joshi
1,123 Expert 1GB
Yup a added that and got the output.

But it is not similar to object.toString() in java right?
Jul 22 '09 #5
Markus
6,050 Expert 4TB
@dheerajjoshim
Why is it not?

Mark.
Jul 22 '09 #6
Atli
5,058 Expert 4TB
@dheerajjoshim
The only difference, really, is in the spelling.
Both serve to provide a string representation of the object, and both need to be implemented specifically for an object to provide an accurate representation. (Otherwise you just get a generic "object" string, or nothing at all)

But you should keep in mind that PHP and Java are two extremely different languages, and things may not be implemented the same way between the two, if they are implemented at all.
Jul 22 '09 #7

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

7 posts views Thread by BBFrost | last post: by
6 posts views Thread by Joe | last post: by
8 posts views Thread by John Cobb | last post: by
7 posts views Thread by Dylan Parry | last post: by
1 post views Thread by ivansh | last post: by
8 posts views Thread by Phil Jollans | last post: by
reply views Thread by zhoujie | last post: by
1 post views Thread by Marylou17 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.