Often you need classes with similar variables and functions
to another existing class. In fact, it is good practice to
define a generic class which can be used in all your
projects and adapt this class for the needs of each of your
specific projects. To facilitate this, classes can be
extensions of other classes. The extended or derived class
has all variables and functions of the base class (this is
called 'inheritance' despite the fact that nobody died) and what
you add in the extended definition. It is not possible to
subtract from a class, that is, to undefine any existing
functions or variables. An extended class is always dependent
on a single base class, that is, multiple inheritance is
not supported. Classes are extended using the keyword 'extends'.
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:
This is also called a "parent-child" relationship. You create a class,
parent, and use extends to create a new class
based on the parent class: the child class. You can
even use this new child class and create another class based on this child
class.
Note:
Classes must be defined before they are used! If you want the class
Named_Cart to extend the class
Cart, you will have to define the class
Cart first. If you want to create another class called
Yellow_named_cart based on the class
Named_Cart you have to define
Named_Cart first. To make it short: the order in which
the classes are defined is important.