Today we are going to learn how autoloader works in PHP. Let’s say we have a file student.php which have a class name student I want to use this class instance somewhere in other files. For example, I am using index.php if I want to create an instance of the student class then first I have to include student.php., These are the functions. We can use this functions to include code from other files.
include
include_once
require
require_once
If we want to use the class student in the index, we should do something like this:
<?php //We are here in index.php //this will include student.php in current file include "student.php"; //here i have created instance for student this class is created in student.php $student1 = new student();
So far seems easy to do this stuff. Now if we have to include more than one file then we will write include function to each and every file to include them inside index file. Now this is normal process without an autoloader
<?php include "student.php"; include "marks.php"; include "teacher.php"; .. . //there are more files to include we will write for each in same way //this will take to much time and space if number of files are more . . include "exam.php"; //create instance for each class $john = new student();
This is usual way for files to be loaded. Same task we can perform with autoloader in php but we will reduce some code which will save your time. Autoloader does same as the name says, it automatically loads a class whenever they are needed.
Look at this example:
<?php //create function which will first store the path of that into a file variable function auto_loader($class) { $file = "{$class}.php"; //this will check if file exist if (is_file($file)) { //finally if file exist then it will include the file include $file; } } spl_autoload_register("auto_loader"); $john = new student(); // File will be autoloaded here
This is a very easy process. I have created a function name auto_loader() and it receives a class name to be the load. Inside this function, I have created a variable $file with the full path to the file to be included. Then I have checked if the file exists, if the file exists then it will include the file. Then I used the spl_autoload_register() function to let PHP know that it can also use auto_loader() to find a class. At last, I have created an instance of class student now all these above processes will take place. It will only load file student which have class name student, not all the files.
Be the first to comment.