Need of PHP Autoload function: -
When the number of classes grows, it is quite tedious to call require_once() function everywhere
you use the classes. Fortunately, PHP provides a mechanism that allows you to load class files
automatically whenever you try to create an object from a non-existent class in the context of the
current script file.
PHP Autoload function: - PHP will call __autoload() function automatically whenever you create an object from a nonexistent class. __autoload() which is automatically called when your code references a class or interface that hasn't been loaded yet. The major drawback to the __autoload() function is that you can only provide oneautoloader with it.
Syntax:- autoload.php function __autoload($className) { $className = str_replace('..', '', $className); require_once("classes/$className.php"); } This autoload.php file must be include/require in your page to run autoloader
Demo.php- it is a sample class
a=$a; } public function getA(){ return $this->a; } } ?>
autoload.php- it is a autoload class which should be included whenever you want to use autoload functionality index.php- A sample use of autoload.php setA(10); echo "Value of A:".$d1->getA(); ?>
PHP Autoload function: - PHP will call __autoload() function automatically whenever you create an object from a nonexistent class. __autoload() which is automatically called when your code references a class or interface that hasn't been loaded yet. The major drawback to the __autoload() function is that you can only provide oneautoloader with it.
Syntax:- autoload.php function __autoload($className) { $className = str_replace('..', '', $className); require_once("classes/$className.php"); } This autoload.php file must be include/require in your page to run autoloader
Demo.php- it is a sample class
a=$a; } public function getA(){ return $this->a; } } ?>
autoload.php- it is a autoload class which should be included whenever you want to use autoload functionality index.php- A sample use of autoload.php setA(10); echo "Value of A:".$d1->getA(); ?>
Comments
Post a Comment