We continue with the Part III of our coding technique,
the Inheritance or "Subclasses".
In lesson I we have learned, what is Inheritance and what this can do for you. Because PortaMx use these technique , we want to get examples of "Subclasses".
First we have to define a "root" class like this:
// the class definition
class Cat
{
var $name; // class attribute
// the constructor
function Cat($name)
{
$this->name = $name;
}
// a method
function showCat()
{
echo 'This cat have the name '. $this->name;
}
}
Now we create a "Subclass" from the root class:
// the class definition
class Cats extends Cat
{
var $color; // class attribute
// the constructor
function Cats($name, $color)
{
$this->Cat($name); // call the "root" constructor
$this->color = $color;
}
// a method "overload"
function showCat()
{
echo 'This '. $this->color .' cat have the name '. $this->name;
}
}
Now we create a instance from the "root class" Cat:
$class = 'Cat';
$rootclass = new $class('Finja');
$rootclass->showCat();
This will display the string
This cat have the name Finja.
Now we create a instance from the "Subclass" Cats:
$class = 'Cats';
$handle = new $class('Lucy', 'brown-white');
$handle->showCat();
This will display the string
This brown-white cat have the name Lucy.
We create a second instance from the "Subclass" Cats:
$class = 'Cats';
$handle2 = new $class('Jenny', 'red tabby');
$handle2->showCat();
This will display the string
This red tabby cat have the name Jenny .
In this example you see, that the subclass have only a attribute ($color) they are not available in the root class.
Furthermore we use here a other OOP functionality .. the method overload (or overwrite). This is a specially technique to expand or modify a existing method in a parent class.
Also you have to note, that a "Subclass" do not MUST have a constructor. If no constructor defined, the parent constructor is called automatically.
To be continued ...
Fel