Extends class

Extends a class within php, as described in more detail here. Basically is making a second class extended from the first class with either making amendments to some of the functions or adding some, this makes the second class the version 2 from the first class (version 1).

The extended class can still call the parent (version 1) class via the

parent::<function etc to call>

syntax, which basically means, calling the parent class to do something, for example the parent class may setup the variables of a array whilst the extended version 2 class may sort them into alphabetical order.

Here some code that may make more sense.

<?php
 
/* the base class, version 1 as such of a class */
class BaseClass {
    function HiFromMe()
    {
	echo "\nHi from the base class\n";
    }
 
    function BaseFunction()
    {
	echo "\nHi from base function\n";
    }
}
 
/* the extended class, this extends from the base class to make it a better (version 2) class */
class ExtendedClass extends BaseClass {
    function HiFromMe()
    {
	echo "\nHi from the extended class\n";
    }
 
    function CallBaseFunction()
    {
	echo "\nCalling base (parent) class";
	// need to put parent:: which means call the parent class
	parent::BaseFunction();
    }
}
 
$base = new BaseClass();
 
$base->HiFromMe();
$base->BaseFunction();
 
$extended = new ExtendedClass();
 
$extended->HiFromMe();
echo "\nYou can still call the base functions because you extended it";
$extended->BaseFunction();
echo "\nTo call from within a function";
$extended->CallBaseFunction();
?>
 
and the output would be... 
 
<pre lang="bash">
Hi from the base class
 
Hi from base function
 
Hi from the extended class
 
You can still call the base functions because you extended it
Hi from base function
 
To call from within a function
Calling base (parent) class
Hi from base function

One thought on “Extends class”

Leave a Reply

Your email address will not be published.