PHP

PHP – __autoload() & SPL

__autoload() called anytime a new object attempts to be instantiated

As a programmer, at least we need to include certain classes or files before we execute files. __autoload() will be a good place to include all required classes or files.

But we only able to define only one __autoload() and this may cause problem to people writing third-party libraries or codes since they might have already define this __autoload().

Use spl_autoload_register() to add multiple autoloading into SPL(Standard PHP Library)

function autoload_one()
{
	@require_once "CD.php";
	echo '<p>CD Class Loaded.</p>';
}

spl_autoload_register('autoload_one');

function autoload_two()
{
	@require_once "ARTIST.php";
	echo '<p>ARTIST Class Loaded.</p>';
}

spl_autoload_register('autoload_two');

$mydisk = new CD();
$myartist = new ARTIST();

var_dump(array($mydisk,$myartist));

Using @ before require_once to prevent errors to be thrown when one function tries to load the file but fails

One last thing about __autoload() and SPL, what if __autoload has been declared? So, here the solution.

function __autoload($classname)
{
	@require_once "CD.php";
}

function autoload_two()
{
	@require_once "ARTIST.php";
	echo '<p>ARTIST Class Loaded.</p>';
}

if(function_exists('__autoload'))
{
	spl_autoload_register('__autoload');
	echo '<p>CD Class Loaded.</p>';
}

spl_autoload_register('autoload_two');

$mydisk = new CD();
$myartist = new ARTIST();

var_dump(array($mydisk,$myartist));

p/s: I chose the last method to use __autoload() and SPL together, much clean & convenient.

Leave a Reply

Your email address will not be published. Required fields are marked *

1 × 3 =