PHP design pattern study notes one-about automatic loading of PHP classes

PHP design pattern study notes one-about automatic loading of PHP classes

Preface

When the engineering-level code needs to import a lot of external files, it will cause a lot of code similar to the following to be written in the head of the class file:

require_once __DIR__.'/'.$class.'.php';
 

In this case, we can use __autoload()functions to automatically load classes, but due to the problem of the same function names, PHP officials currently recommend using spl_autoload_register()functions instead of __autoload()functions, because we can define the name of the function for auto-loading classes by ourselves, and then in the spl_autoload_register()function Implement the calls of these classes.

Code demo

Define two test classes Test1.phpand Test2.phpa test entry classTest.php

Test1.php

<?php
class Test1{
    static function test(){
        echo __METHOD__."\n";
    }
}
 

Test2.php

<?php
class Test2{
    static function test(){
        echo __METHOD__."\n";
    }
}
 

Test entry class

<?php

spl_autoload_register('autoload1');
Test1::test();
Test2::test();

function autoload1($class){
    require_once __DIR__.'/'.$class.'.php';
}
 

You can see that we have customized the auto-loading function of a class in the entry class, autoload1()and then spl_autoload_register()declared the call of the auto-loading function in the function.

operation result

/usr/bin/php/Users/yang/PHPCode/Test.php
Test1::test
Test2::test

Process finished with exit code 0
 

You can see that the methods in different classes have been successfully called, and the program has not reported an error.