Home > Backend Development > PHP Tutorial > Detailed explanation of the usage of php function spl_autoload_register

Detailed explanation of the usage of php function spl_autoload_register

WBOY
Release: 2016-07-25 08:56:42
Original
1064 people have browsed it
  1. class A{
  2.  public function __construct(){
  3.   echo 'Got it.';
  4.  }
  5. }
Copy code

Then, there is an index.php that needs to be used To this class A, the conventional writing method is:

  1. require('A.php');

  2. $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:

  1. function __autoload($class) {

  2.   $file = $class . '.php';
  3.  if (is_file($file)) {
  4.   require_once($file ; Define the rules for loading classes with __autoload.

  5. 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);
      }
     }
      }

    1. spl_autoload_register(array('Loader', 'loadClass'));

    2. $a = new A();

    3. Copy code
    source:php.cn
    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template