how to autoload classes in php code example

Example 1: 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 2: 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