note 86096 added to language.oop5.magic

From: Date: Thu, 02 Oct 2008 23:12:32 +0000
Subject: note 86096 added to language.oop5.magic
Groups: php.notes 
Request: Send a blank email to php-notes+get-145000@lists.php.net to get a copy of this message
To be helpful, the __toString() method should return the class name and the state of all its properties inside square brackets. <?php class Point { protected $x, $y; public function __construct($xVal = 0, $yVal = 0) { $this->x = $xVal; $this->y = $yVal; } public function __toString() { // the function we're interested in... return "Point[x=$this->x, y=$this->y]"; } } $point1 = new Point(10, 10); $point2 = new Point(50, 50); echo $point1 . '<br>'; echo $point2 . '<br><br>'; ?> Point[x=10, y=10] Point[x=50, y=50] Classes that include objects, should call that objects __toString() method. <?php class Line { protected $start, $end; public function __construct(Point $p1, Point $p2){ $this->start = $p1; $this->end = $p2; } public function __toString() { // the function we're interested in... return 'Line[start=' . $this->start->__toString() . // call __toString() ', end=' . $this->end->__toString() . ']'; // call __toString() } } echo (new Line($point1, $point2)); ?> Line[start=Point[x=10, y=10], end=Point[x=50, y=50]] ---- Server IP: 69.147.83.197 Probable Submitter: 67.150.124.17 ---- Manual Page -- http://www.php.net/manual/en/language.oop5.magic.php Edit -- https://master.php.net/note/edit/86096 Del: integrated -- https://master.php.net/note/delete/86096/integrated Del: useless -- https://master.php.net/note/delete/86096/useless Del: bad code -- https://master.php.net/note/delete/86096/bad+code Del: spam -- https://master.php.net/note/delete/86096/spam Del: non-english -- https://master.php.net/note/delete/86096/non-english Del: in docs -- https://master.php.net/note/delete/86096/in+docs Del: other reasons-- https://master.php.net/note/delete/86096 Reject -- https://master.php.net/note/reject/86096 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#145000) next »