“This is the 16th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”

Curriculum background

  • I recently completed a project that had a slight understanding of code layering but had problems with architectural design rationality
  • Look at the essence of everythingThe basics are hard and the underlying knowledge is solid so that you can write better code and go further
  • Once again, I’m brushing up on the basics of THINKING about design patterns and PHP as a struggling programmer
  • As the gold digger got a reward, he took notes and shared them.

The text start

When PHP project more and more and more large files, so if you need to use to some kind of needs in the top write a heap of introduced the require statement, if you remove a single class file, the other file can’t find this file will be submitted to a fatal error. This approach is difficult to maintain manually, so you need a method that automatically loads classes.

1. Initial implementation methodThe initial method was implemented by magic method, but this method still has the problem of duplicate method names in multiple files.

So now we all use the spl_autoload_register() method

2 Define the spl_autoload_register callback function. If the class cannot be found, the spl_AUtoload_register callback function is automatically executed

One of the silly things I just did was register autoload, but the callback didn’t execute. That’s because spl_autoload_register is for classes that can’t be found, and when executing methods defined in other namespaces, it definitely won’t start the auto-load. Remember to remember here.

Define classes in the test1.php file


      
namespace t1;

class Test1{
    static function hello(){
        echo __FILE__; }}Copy the code

Index.php file


      
spl_autoload_register(function($class){
    echo "This is auto-loading.".$class;
    // echo './' . $class . '.php';
    // require './' . $class . '.php';
});

\t1\Test1::hello();  // Specify the namespace
Copy the code

Because it follows the PSR-0 specification, $class carries things like namespaces, which will be explained in the next section, and what is the PSR-0 specification