Autoloading classes in PHP

When I was analysing about the different framework, they structure are little different but loading the classes are almost same way.

Why we need autoload for classes ?

Autoload use to load the classes, if you create the object for GetOutput class it will automatically call the filename. Thus filename and class name should be same. Without auto-loading we need to include the filename to create the object.

Let’s create simple class, which will print the value from the class.

GetOutput.php

class GetOutput  
{	 
    	function __construct() {
      		echo "Welcome to GetOutput";
    	}
}

index.php

<?php
// creating autoload function which will include the filename
function __autoload($class_name) { include $class_name.".php"; }

$obj = new GetOutput;

PHP also support to load the customized auto-load function using spl_autoload_register.

<?php
// creating customized function to include the filename of that class
function myAutoload($class_name) { include $class_name.".php"; }

// registering the customized function 
spl_autoload_register('myAutoload');

$obj = new GetOutput;

You can also set the file extension using spl_autoload_extensions function in auto-load.

<?php

function myAutoload($class_name) { include $class_name; }

// registering the file extension to be loaded with filename
spl_autoload_extensions(".php");
spl_autoload_register();

$obj = new GetOutput;
// registering the customized function
spl_autoload_register('myAutoload');

 

Share