A class is a collection of variables and functions working with
these variables. A class is defined using the following syntax:
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.
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.
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:
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.
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.
Caution |
For derived classes, the constructor of the parent class is not
automatically called when the derived class's constructor is
called.
|