note 85151 deleted from language.oop5 by danbrown
| From: | danbrown@php.net | Date: | Wed, 17 Jun 2009 18:49:23 +0000 |
| Subject: | note 85151 deleted from language.oop5 by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-157015@lists.php.net to get a copy of this message | ||
Note Submitter: wbcarts at juno dot com
----
Sorry to change the subject, but OOP is way cooler if you "define" and "use"
several objects in combination with each other.
<?php
class Point{ // an object that represents a location in 2-dimensional
space.
public $x; // x position of this point
public $y; // y position of this point
public function __construct($xPos = 0, $yPos = 0){
$this->x = $xPos;
$this->y = $yPos;
}
public function __toString(){ // get a string representation of this point
return 'Point(' . $this->x . ', ' . $this->y .')';
}
}
class Line{ // an object that represents a line in 2-dimensional space
public $start; // start point of this line
public $end; // end point of this line
public function __construct($xPos1 = 0, $yPos1 = 0, $xPos2 = 0, $yPos2 = 0){
$this->start = new Point($xPos1, $yPos1); // create a Point object
$this->end = new Point($xPos2, $yPos2); // create a Point object
}
public function getLength(){ // get the length of this line
return sqrt(
pow(($this->start->x - $this->end->x), 2) +
pow(($this->start->y - $this->end->y), 2)
);
}
public function __toString(){ // get a string representation of this line
return 'Line[start=' . $this->start . ', end=' . $this->end .
', length=' . $this->getLength() . ']';
}
}
// create a few objects of TYPE Line.
$line1 = new Line(25, 25, 40, 40);
$line2 = new Line(10, 10, 30, -10);
$line3 = new Line(-50, 65, 50, 65);
// output to the display
echo '<p>$line1 = ' . $line1 . '</p>
<p>$line2 = ' . $line2 . '</p>
<p>$line3 = ' . $line3 . '</p>';
?>
-- Begin output --
$line1 = Line[start=Point(25, 25), end=Point(40, 40), length=21.2132034356]
$line2 = Line[start=Point(10, 10), end=Point(30, 0), length=22.360679775]
$line3 = Line[start=Point(-50, 65), end=Point(50, 65), length=100]
-- End output --
Each of the objects created above ($line1, $line2, $line3) are of TYPE Line, and each one can
perform their own special tasks which includes; creating the start and end points, and calculating
its length. The start and end points are created in the constructor when the Line is created, and
the length is calculated in the __toString method when the Line is called to be displayed, although,
you can call the getLength() method at any time. Having individual objects work on themselves this
way is one of the really cool things about OOP, and allows you to create more complicated software.