Quantcast
Channel: Webkul Blog
Viewing all articles
Browse latest Browse all 5489

Autoloading in PHP

$
0
0

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 file. For example i am using index.php if i want to create 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 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 for seems easy to do these stuff .Now if we have to include more than one file then we will write incude function to each and every file to include them inside index file. Now this is normal process without 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 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 very easy process. I have created a function name auto_loader() and it receives a class name to be load. Inside the 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 exist . if yes 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 a instance of class student now all these process will be take place. It will only load file student which have class name student. Not all the files .

 

 


Viewing all articles
Browse latest Browse all 5489

Trending Articles