Autoloading objects – an overview
- Tuesday, March 10, 2009, 9:43
- PHP & MySQL
- Add a comment
One of my amigo last week put up a question towards me seeking a clear riposte on what’s exactly this autoloading does. I thought of putting this up here on what i scribbled in the piece of paper to explain him.
What is Autoloading objects?
How about we including the classes automatically. puzzled right! Normally to include a class, you would go on with either ( include or require ) languager construct. By using __autoload function defined, inclusion will handle itself. I will explain you clearly further citing the traditional way as well as new approach.
Traditionally we would go in this fashion
include “classes/class.vinoth.php”;
$vinoth = new Vinoth;
$vinoth->methodname();
With our new approach….
function
__autoload($class_name)
{
require_once $DOCUMENT_ROOT.“classes/class.”.$class_name.“.php”;
}
$vinoth = new Vinoth;
$vinoth->methodname();
Here, if Vinoth is created for the first time then the __autoload function is called automatically.Normally everydevelopers follow their own style of coding. I have used autoload in a different fashion irrespective of the listed above. I normally set the ini_set or set_include_path before hand and make the __autoload function much simpler just including the class name.
Note: We can also make throw expections instead of fatal error, if the classes are not loaded.
Popularity: 1% [?]
About the Author
Write a Comment
Gravatars are small images that can show your personality. You can get your gravatar for free today!