Analysis of Implementation Method of Automatic Loading Mechanism of PHP Class

  • 2021-11-13 01:09:29
  • OfStack

This paper describes the implementation method of automatic loading mechanism of PHP class with examples. Share it for your reference, as follows:

Test1.class.php


<?php
class Test1
{
  public static function test() {
    echo "hello,world!\n";
  }
}

Test2.class.php


<?php
class Test2
{
  public static function test() {
    echo " Hello, world !\n";
  }
}

test.php


<?php
Test1::test();

If you write directly, you will report an error

Fatal error: Class 'Test1' not found in /home/wwwroot/default/codelabs/test.php on line 3

Need to import files


<?php
require "Test1.class.php";
Test1::test();

So you can access it.

However, if there are more classes, more and more code will be introduced.

You need to use it at this time __autoload Method.


<?php
Test1::test();
function __autoload($class) {
  //require "Test1.class.php";
  //require "Test2.class.php";
  require __DIR__."/".$class.".class.php"; // __DIR__ Is the absolute path to the current directory 
}

When the program finds that no class is introduced, it will automatically call this method and introduce the class file.

Take one step to optimize and upgrade,

Multiple auto-loads are supported.


<?php
spl_autoload_register('__autoload1');
spl_autoload_register('__autoload2');
Test1::test();
Test2::test();
//  This method is automatically called when a classless load is detected 
function __autoload1($class) {
  //require "Test1.class.php";
  //require "Test2.class.php";
  require __DIR__."/".$class.".class.php"; // __DIR__ Is the absolute path to the current directory 
}
function __autoload2($class) {
  //require "Test1.class.php";
  //require "Test2.class.php";
  require __DIR__."/".$class.".class.php"; // __DIR__ Is the absolute path to the current directory 
}

Very good, very powerful!

For more readers interested in PHP related content, please check the topics on this site: "Introduction to php Object-Oriented Programming", "Encyclopedia of PHP Array (Array) Operation Skills", "Introduction to PHP Basic Syntax", "Summary of PHP Operation and Operator Usage", "Summary of php String (string) Usage", "Introduction to php+mysql Database Operation" and "Summary of php Common Database Operation Skills"

I hope this article is helpful to everyone's PHP programming.


Related articles: