note 86096 deleted from language.oop5.magic by cmb
| From: | cmb@php.net | Date: | Sun, 10 Nov 2019 12:35:12 +0000 |
| Subject: | note 86096 deleted from language.oop5.magic by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-212979@lists.php.net to get a copy of this message | ||
Note Submitter: wbcarts at juno dot com
----
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]]