PHP automatically load

When writing object-oriented (OOP) program, many developers for each class to create a new PHP file. This will bring a trouble: at the beginning of each script, you need to include (include) a long list (every class has a file).

 

From PHP 5, may be used  spl_autoload_register ()  register any function of the number of autoloader, when a class (class) used when the interface has not been defined (interface) and to load automatically.

By registering the autoloader, the script engine had a last chance to load the required class before PHP fails in error.

 

Code Example:

a.php

<?php
class A {
    public function __construct() {
        echo "class A<br>";
    }
}

 

b.php

<?php
class B {
    public function __construct() {
        echo "class B<br>";
    }
}

 

index.php

<?php
spl_autoload_register(function ($class) {
    require __DIR__ . '/' . $class . '.php';
});

$a = new A;
$b = new B;

自动加载In a class is our new time, do not need to manually write class.php require to import the file, the program automatically help us load import come.

 

SPL Autoload

SPL is the abbreviation for Standard PHP Library (Standard PHP Library) is. It is an extension library PHP5 introduced to achieve its main function includes autoload Iterator mechanism and includes various classes or interfaces. SPL Autoload has several specific functions:

spl_autoload_register: Registration _autoload () function
spl_autoload_unregister: cancellation of registered functions
spl_autoload_functions: return all the registered function
spl_autoload_call: try all functions registered to load class
spl_autoload: _autoload () default implementation
spl_autoload_extionsions: Sign and return spl_autoload function uses the default file extension

 

Guess you like

Origin www.cnblogs.com/ryanzheng/p/12571932.html