Final and auto load a class

To include a class within many languages you have to define it at the top and then off you go with programming with using that class. Well within PHP you can use the __autoload function that is called when you try to create a new instance of a class.

function __autoload($class_name) 
{
	include "classes/".$class_name.".php";
}

this __autoload function above takes a parameter as the class name to load and then within the code it will try and load that class with how ever you want to, in this case I have placed the classes within the directory called classes and under there classname.php filename.

So if you try to load the class

$newclass = new basic();

it will look within the classes directory for the file basic.php for the autoload function above, you can alter it to load from where ever and how ever you want to.

The next part of this post is about the keyword ‘final’, the final keyword means that it is final so if you try and extend that class and extend the function that has been declared as final this will cause php interpretor to fail due to syntax error with something similar to

Fatal error: Cannot override final method class_name::function_name()

For an example here is two classes one is called basic and the other is called extendbasic, where the basic class has the final function within it

class basic
{
	public function sayHello()
	{
		echo "<br/>".get_class($this) . " : Hello";
	}
 
	final public function sayGoodbye()
	{
		echo "<br/>".get_class($this) . " : Goodbye";
	}
}

and here is the extendclass

class extendbasic extends basic
{
	public function sayHello()
	{
		echo "<br/>".get_class($this). " : the newer hello!!";	
		parent::sayHello();
	}
        // this will cause the php engine to fail!!!!!. because it is trying to over load the function sayGoogbye which has been declared as final
/*	public function sayGoodbye()
	{
		echo "I should not get here!!";
	}*/
}

Here is some code to call them both which they have been placed within a directory called ‘classes’

function __autoload($class_name) 
{
	include "classes/".$class_name.".php";
}
 
$basicClass = new basic();
$basicClass->sayHello();
$basicClass->sayGoodbye();
$basicClass = new extendbasic();
$basicClass->sayHello();
$basicClass->sayGoodbye();

and the output would be

basic : Hello
basic : Goodbye
extendbasic : the newer hello!!
extendbasic : Hello
extendbasic : Goodbye

I am calling the parent function from within the extendbasic class sayHello function.

Leave a Reply

Your email address will not be published. Required fields are marked *