<?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.
|