Is there a way I can define __autoload in a class, so whenever I access an undefined class PHP will run the __autoload class method?
<?php
class Test {
public function __construct() {
echo 'Instantiating ', __CLASS__, "\n";
}
public function __autoload($className) {
echo "Loading $className\n";
require_once($className . '.php');
}
public function test() {
$test = new AnotherClass();
}
}
$bill = new Test();
$bill->test();
AnotherClass.php:
<?php
class AnotherClass {
public function __construct() {
echo 'Instantiating ', __CLASS__, "\n";
}
}
Output:
Instantiating Test Loading AnotherClass Instantiating AnotherClass
No, the
__autoloadfunction must be global.However,
SPLhas a way to register any callable as an autoload function:spl_autoload_register(). It does not make much sense to use a class method though – you’d probably just create the instance, register the method and never use that instance again.