note 86229 deleted from language.oop5 by googleguy

From: Date: Tue, 15 Jan 2013 04:43:56 +0000
Subject: note 86229 deleted from language.oop5 by googleguy
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-193052@lists.php.net to get a copy of this message
Note Submitter: Jeffrey ---- 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.

« previous php.notes (#193052) next »