-
- class A{
- public function __construct(){
- echo 'Got it.';
- }
- }
-
Copy code Then, there is an index.php that needs to be used To this class A, the conventional writing method is:
require('A.php'); - $a = new A();
-
Copy code
Problem :
If index.php needs to contain not just class A, but many classes, you must write many lines of require statements.
In php5, the __autoload function is automatically called when trying to use a class that has not been defined, so you can let php automatically load the class by writing the __autoload function.
The above example can be modified as:
-
-
function __autoload($class) { - $file = $class . '.php';
- if (is_file($file)) {
- require_once($file ; Define the rules for loading classes with __autoload.
-
-
-
- Copy code
-
In addition, if you don’t want to call __autoload when loading automatically, but call your own function (or class method), you can use spl_autoload_register to register your own autoload function.
The function prototype is as follows:
bool spl_autoload_register ( [callback $autoload_function] )
Continue to modify the above example:
function loader($class) { $file = $class . '.php';
if (is_file($file)) {
require_once($file
Copy the code
php does not call __autoload when looking for a class but calls the self-defined function loader.
The following writing methods are also possible, for example:
class Loader { public static function loadClass($class) { $file = $class . '.php'; if (is_file($file)) { require_once($file); } } } spl_autoload_register(array('Loader', 'loadClass'));
$a = new A();
-
-
-
- Copy code
-
-
-
-
-
-
-
-
|