|
|
|
|
| Tutorial |
Chapter 2 Advanced Syntax
{
if($this->item_list[$item] > $quantity)
$this->item_list[$item] -= $quantity;
else
$this->item_list[$item] = 0;
}
}
The constructor, contained in shopping_cart::shopping_cart(), takes two optional
arguments—if no arguments are specified, upon instantiation the shopping cart will
“prefill” itself with one T-Shirt. Otherwise, it will take the wanted items:
$default_cart = new shopping_cart; // this cart will fill itself with
➥one T-Shirt by default
$mug_cart = new shopping_cart(“Mug”, 2); // this cart will contain two mugs
Inheritance
Adding functions to objects shouldn’t be done by rewriting old code but by
overloading existing structures instead. New objects can inherit from old objects by
using the keyword extends. As the name suggests, this will define a new class that
extends an existing one:
class extended_cart extends shopping_cart
{
function query($item)
{
return($this->item_list[$item]);
}
}
This extended cart extended_cart now contains all properties and member functions
from shopping_cart with the addition of another function, query(), which allows us
to check the quantity of any given item in the cart.
Note: The class extended_cart doesn’t have its own constructor. If a child class
doesn’t have a constructor, PHP (since version 4.0) automatically calls the parent’s
constructor. However, by default PHP will never call a parent’s constructor.Thus, if
you need to set up your parent object, make sure that you call its constructor
manually.
|
|
|
|
|
|
| Link Partners: Asia florist, Flowers to India, Hong kong flowers, Site submit, Cheap web hosting, China florist, Japan florist |
|