| Newsgroups |
php.notes |
| Message-ID |
<[email protected]> |
Why should anyone learn what classes and objects are? The short answer is to clarify and simplify code. Take this regular script:
<?php
$item_name = 'Widget 22';
$item_price = 4.90;
$item_qty = 2;
$item_total = ($item_price * $item_qty);
echo "You ordered $item_qty $item_name @ \$$item_price for a total of: \$$item_total.";
?>
You ordered 2 Widget 22 @ $4.9 for a total of: $9.8.
You can see clearly that you have to "define and set" the data, "perform a calculation", and explicitly "write" the results - for a total of 5 written statements. But the more you look at it, the more it needs fixin'. If you attempt to do that, your code can get really ugly, really fast - and remember, this is just a simple script! Here's the same program in OOP with all the fixin's:
<?php
class Item {
protected $name, $price, $qty, $total;
public function __construct($iName, $iPrice, $iQty) {
$this->name = $iName;
$this->price = $iPrice;
$this->qty = $iQty;
$this->calculate();
}
protected function calculate() {
$this->price = number_format($this->price, 2);
$this->total = number_format(($this->price * $this->qty), 2);
}
public function __toString() {
return "You ordered ($this->qty) '$this->name'" . ($this->qty == 1 ? "" : "s") .
" at \$$this->price, for a total of: \$$this->total.";
}
}
echo (new Item("Widget 22", 4.90, 2));
?>
You ordered (2) 'Widget 22's at $4.90, for a total of: $9.80.
By loading class Item (which houses all the improvements we made over the first script) into PHP first, we went from having to write 5 statements in the first script, to writing only 1 statement "echo new Item" in the second.
----
Server IP: 69.147.83.197
Probable Submitter: 67.150.124.108
----
Manual Page -- http://www.php.net/manual/en/language.oop5.php
Edit -- https://master.php.net/note/edit/86229
Del: integrated -- https://master.php.net/note/delete/86229/integrated
Del: useless -- https://master.php.net/note/delete/86229/useless
Del: bad code -- https://master.php.net/note/delete/86229/bad+code
Del: spam -- https://master.php.net/note/delete/86229/spam
Del: non-english -- https://master.php.net/note/delete/86229/non-english
Del: in docs -- https://master.php.net/note/delete/86229/in+docs
Del: other reasons-- https://master.php.net/note/delete/86229
Reject -- https://master.php.net/note/reject/86229
Search -- https://master.php.net/manage/user-notes.php