Categories
PHP

Autoloading Classes in PHP

When a programmer doing a object oriented application then he/she need to use properties or method of different classes. Then the programmer need to include / include_once / require / require_once of that class file and make a instance of that class. Sometime they need to do the same things several times. So it is really boring and full of hassle. In this case you can make a autolader in your application, and reduce your code and time as well as hassle.

I have written a autoloader. Hope you guys are easily understand that. Lets see.

MyClass.php

<?php
/**
 * @Author: Sohel Rana
 * @URI : http://www.sohelranabd.com
 * @Description: This is simple example of PHP auto loading class
 */

class MyClass  // Creating First Class
{
    public function getValue(){
        return "This is MyClass Class";
    }
}

 

MyClass2.php

<?php
/**
 * @Author: Sohel Rana
 * @URI : http://www.sohelranabd.com
 * @Description: This is simple example of PHP auto loading class
 */

class MyClass2  // Creating Second Class
{
    public function getValue(){
        return "This is MyClass 2 Class";
    }
}

 

index.php

<?php
/**
 * @Author: Sohel Rana
 * @URI : http://www.sohelranabd.com
 * @Description: This is simple example of PHP auto loading class
 */

function __autoload($className){
    $fileName = $className.'.php';
    include_once($fileName);
}

$OBJ1 = new MyClass();    // Creating instance of MyClass
echo $OBJ1->getValue();   // Calling getValue() function of MyClass class

$OBJ2 = new MyClass2();    // Creating instance of MyClass2
echo $OBJ2->getValue();   // Calling getValue() function of MyClass2 class

 

Here you can see the __autoload() function. This function is automatically load you desire class files. So you just need to create a instance of your classes. It is really easy and does not need to include your class file again and again.

This is the simple way of creating a auto loader in PHP.