__toString()

  • Bogey
  • Genius
  • Genius
  • Bogey
  • Posts: 8397
  • Loc: USA

Post 3+ Months Ago

I still (after reading the PHP tutorial we have here) don't understand the __toString() method... well, I kind of understand what it does, but what's the use of it?


Also, it would have been awesome if there was a magic method that was invoked before and after an invoked available method was called. Maybe a different magic method for each function.
  • Anonymous
  • Bot
  • No Avatar
  • Posts: ?
  • Loc: Ozzuland
  • Status: Online

Post 3+ Months Ago

  • spork
  • Brewmaster
  • Silver Member
  • User avatar
  • Posts: 6252
  • Loc: Seattle, WA

Post 3+ Months Ago

__toString() is what's called when someone tries to cast an object to a string. Usually you'd use it to define a string representation of whatever it is your class actually represents.

For example, if you had a Shoe class (I don't know, maybe you're running a shoe store or something), you might define __toString() to output something like:

PHP Code: [ Select ]
class Shoe
{
    private $brand = '';
    private $product = '';
    private $size = 0;
 
    function __construct($brand, $product, $size)
    {
        $this->brand = $brand;
        $this->product = $product;
        $this->size = $size;
    }
 
    function __toString()
    {
        echo $this->brand . ' ' . $this->product . ', size ' . $this->size;
    }
}
  1. class Shoe
  2. {
  3.     private $brand = '';
  4.     private $product = '';
  5.     private $size = 0;
  6.  
  7.     function __construct($brand, $product, $size)
  8.     {
  9.         $this->brand = $brand;
  10.         $this->product = $product;
  11.         $this->size = $size;
  12.     }
  13.  
  14.     function __toString()
  15.     {
  16.         echo $this->brand . ' ' . $this->product . ', size ' . $this->size;
  17.     }
  18. }


This would let you do something like this:

PHP Code: [ Select ]
$foo = new Shoe('Nike', 'Air Jordan', 11);
echo $foo;
  1. $foo = new Shoe('Nike', 'Air Jordan', 11);
  2. echo $foo;


And this would output:

Code: [ Select ]
Nike Air Jordan, Size 11
  • Bogey
  • Genius
  • Genius
  • Bogey
  • Posts: 8397
  • Loc: USA

Post 3+ Months Ago

Oh, that makes sense now... looking back at that tutorial, I don't know why I couldn't understand it... I think those <h2> (headers) threw me off for some reason. Thanks spork.

Post Information

  • Total Posts in this topic: 3 posts
  • Users browsing this forum: No registered users and 80 guests
  • You cannot post new topics in this forum
  • You cannot reply to topics in this forum
  • You cannot edit your posts in this forum
  • You cannot delete your posts in this forum
  • You cannot post attachments in this forum
 
 

© 1998-2014. Ozzu® is a registered trademark of Unmelted, LLC.