autoloading in php code example

Example 1: autoloader php

Example #1 Autoload example

This example attempts to load the classes MyClass1 and MyClass2 from the files MyClass1.php and MyClass2.php respectively.
<?php
spl_autoload_register(function ($class_name) {
    include $class_name . '.php';
});

$obj  = new MyClass1();
$obj2 = new MyClass2(); 
?>

Example 2: autoload.php

The introduction of spl_autoload_register() gave programmers 
the ability to create an autoload chain, 
a series of functions that can be called to try and load a class or interface. 

For example:

<?php
function autoloadModel($className) {
    $filename = "models/" . $className . ".php";
    if (is_readable($filename)) {
        require $filename;
    }
}

function autoloadController($className) {
    $filename = "controllers/" . $className . ".php";
    if (is_readable($filename)) {
        require $filename;
    }
}

spl_autoload_register("autoloadModel");
spl_autoload_register("autoloadController");

Example 3: autoloading classes

improved version : 
<?php
spl_autoload_register(function($className) {
	$file = __DIR__ . '\\' . $className . '.php';
	$file = str_replace('\\', DIRECTORY_SEPARATOR, $file);
	if (file_exists($file)) {
		include $file;
	}
});

Example 4: autoloading classes

inside root directory create a autoloader.php file and add the following code :
------------------------------------------------------------------------------
<?php
spl_autoload_register(function($className) {
	$file = $className . '.php';
	if (file_exists($file)) {
		include $file;
	}
});

inside your usage file : 
--------------------------
<?php
include 'autoload.php';

$circle = new Circle;
$square = new Square;

Tags:

Php Example