A class is a collection of variables and functions working with these variables. A class is defined using the following syntax:
<?php class Cart { var $items; // Items in our shopping cart // Add $num articles of $artnr to the cart function add_item ($artnr, $num) { $this->items[$artnr] += $num; } // Take $num articles of $artnr out of the cart function remove_item ($artnr, $num) { if ($this->items[$artnr] > $num) { $this->items[$artnr] -= $num; return true; } else { return false; } } } ?> |
This defines a class named Cart that consists of an associative array of articles in the cart and two functions to add and remove items from this cart.
Classes are types, that is, they are blueprints for actual variables. You have to create a variable of the desired type with the new operator.
$cart = new Cart; $cart->add_item("10", 1); |
This creates an object $cart of the class Cart. The function add_item() of that object is being called to add 1 item of article number 10 to the cart.
Classes can be extensions of other classes. The extended or derived class has all variables and functions of the base class and what you add in the extended definition. This is done using the extends keyword. Multiple inheritance is not supported.
class Named_Cart extends Cart { var $owner; function set_owner ($name) { $this->owner = $name; } } |
This defines a class Named_Cart that has all variables and functions of Cart plus an additional variable $owner and an additional function set_owner(). You create a named cart the usual way and can now set and get the carts owner. You can still use normal cart functions on named carts:
$ncart = new Named_Cart; // Create a named cart $ncart->set_owner ("kris"); // Name that cart print $ncart->owner; // print the cart owners name $ncart->add_item ("10", 1); // (inherited functionality from cart) |
Within functions of a class the variable $this means this object. You have to use $this->something to access any variable or function named something within your current object.
Constructors are functions in a class that are automatically called when you create a new instance of a class. A function becomes a constructor when it has the same name as the class.
class Auto_Cart extends Cart { function Auto_Cart () { $this->add_item ("10", 1); } } |
This defines a class Auto_Cart that is a Cart plus a constructor which initializes the cart with one item of article number "10" each time a new Auto_Cart is being made with "new". Constructors can also take arguments and these arguments can be optional, which makes them much more useful.
class Constructor_Cart extends Cart { function Constructor_Cart ($item = "10", $num = 1) { $this->add_item ($item, $num); } } // Shop the same old boring stuff. $default_cart = new Constructor_Cart; // Shop for real... $different_cart = new Constructor_Cart ("20", 17); |
Caution |
For derived classes, the constructor of the parent class is not automatically called when the derived class's constructor is called. |