Home  >  Article  >  Backend Development  >  Use of SPL spl_autoload_register and __autoload methods in php_PHP tutorial

Use of SPL spl_autoload_register and __autoload methods in php_PHP tutorial

WBOY
WBOYOriginal
2016-07-20 10:59:071088browse

In PHP, the spl_autoload_register and __autoload methods are only available in PHP5. Now I will introduce to you how to use these two magic functions. You can learn more about them. ​

The spl_autoload_register() function should be one of the most used and core functions in mainstream frameworks. It can automatically register functions and classes, implement functions similar to __autoload(), simplify the calling and loading of classes, and improve work efficiency. efficiency.

Supported version: PHP 5 >= 5.1.2

As for efficiency issues. The PHP manual says this:

bool spl_autoload_register ([ callback $autoload_function ] )

Register the function into the SPL __autoload function stack. Activate functions in this stack if they are not already active. If the __autoload function has been implemented in your program, it must be explicitly registered in the __autoload stack. Because the spl_autoload_register() function will replace the __autoload function in Zend Engine with spl_autoload() or spl_autoload_call().

spl_autoload_register
(PHP 5 >= 5.1.2)
spl_autoload_register — register __autoload() function
Description
bool spl_autoload_register ([ callback $autoload_function ] )
Register the function into the SPL __autoload function stack. Activate functions in this stack if they are not already active.
If the __autoload function has been implemented in your program, it must be explicitly registered in the __autoload stack. Because
The spl_autoload_register() function will replace the __autoload function in Zend Engine with spl_autoload() or
spl_autoload_call().
Parameters
autoload_function
The autoload function to be registered. If no parameters are provided, the default implementation function of autoload is automatically registered
spl_autoload().
Return value
Returns TRUE on success, FALSE on failure.
Note: SPL is the abbreviation of Standard PHP Library. It is an extension library introduced in PHP5. Its main functions include the implementation of the autoload mechanism and various Iterator interfaces or classes. The SPL autoload mechanism is implemented by pointing the function pointer autoload_func to a self-implemented function with autoloading function. SPL has two different functions, spl_autoload and spl_autoload_call. Different automatic loading mechanisms are implemented by pointing autoload_func to these two different function addresses.

The code is as follows Copy code
 代码如下 复制代码

class autoload
{
  public static function load( $class name )
  {
    $filename = $classname.".class.php";
    if (file_exists($filename )) {
      require_once $filename ;
    }
  }
}
 
function __autoload( $class name )
{
    // 这个是默认的 autoload 方法
    $filename = $classname.".class.php";
    if (file_exists($filename )) {
      require_once $filename ;
    }
}
 
// 注册一个 autoloader
spl_autoload_register( 'autoload::load' );
spl_autoload_register( '__autoload' );
 // 注:下面的类看上去没有定义,但其实系统根据sql_autoload_register提供的路径会自动去搜索
//foo.class.php文件,如果没找到才报错。
$foo = new foo();
$foo ->bar();
?>

class autoload { public static function load( $class name ) { $filename = $classname.".class.php"; If (file_exists($filename )) {        require_once $filename ; } } } function __autoload( $class name ) { // This is the default autoload method $filename = $classname.".class.php"; If (file_exists($filename )) {        require_once $filename ; } } // Register an autoloader spl_autoload_register( 'autoload::load' ); spl_autoload_register( '__autoload' ); // Note: The following classes appear to be undefined, but in fact the system will automatically search for based on the path provided by sql_autoload_register //foo.class.php file, an error will be reported if it is not found. $foo = new foo(); $foo ->bar(); ?>

Under the supplement:

The __autoload method will become invalid after spl_autoload_register because the autoload_func function pointer already points to the spl_autoload method
* You can add the _autoload method to the autoload_functions list

through the following method

spl_autoload_register( '__autoload' );

Also we can use our custom loading method:

The first functional formula:

The code is as follows Copy code
 代码如下 复制代码

function my_own_loader($classname)
{
    $class_file = strtolower($classname).".php";
    if (file_exists($class_file)){
        require_once($class_file);
    }
}
 
spl_autoload_register("my_own_loader");
 
$a = new A();

function my_own_loader($classname)

{

$class_file = strtolower($classname).".php";
 代码如下 复制代码

class Loader
{
    public static function my_own_loader($classname)
    {
        $class_file = strtolower($classname).".php";
        if (file_exists($class_file)){
            require_once($class_file);
        }
    }
}
 
// 通过数组的形式传递类和方法的名称
spl_autoload_register(array("Loader","my_own_loader"));
$a = new A();

If (file_exists($class_file)){

         require_once($class_file);

}
 代码如下 复制代码

static public function myAutoload($class){
  if(file_exists(APPPATH.'models'.DIRECATORY_SEPARATOR.$class.'.php')){
     require_once APPPATH.'models'.DIRECATORY_SEPARATOR.$class.'.php';
  }
}
/**
* 注册加载器
*/
static public function autoload(){
   spl_autoload_register(array(__CLASS__, 'myAutoload'));
   if(class_exists('__autoload')){
      spl_autoload_register('__autoload');
   }
}
MY_Controller::autoload();

} spl_autoload_register("my_own_loader"); $a = new A();
The second type:
The code is as follows Copy code
class Loader { Public static function my_own_loader($classname) {           $class_file = strtolower($classname).".php"; If (file_exists($class_file)){              require_once($class_file); } } } // Pass the names of classes and methods in the form of arrays spl_autoload_register(array("Loader","my_own_loader")); $a = new A();
Example: When the CI framework implements class loading, its corresponding model is also generated.
The code is as follows Copy code
static public function myAutoload($class){ if(file_exists(APPPATH.'models'.DIRECATORY_SEPARATOR.$class.'.php')){ ​​ require_once APPPATH.'models'.DIRECATORY_SEPARATOR.$class.'.php'; } } /** * Register loader*/ static public function autoload(){ spl_autoload_register(array(__CLASS__, 'myAutoload')); If(class_exists('__autoload')){ spl_autoload_register('__autoload'); } } MY_Controller::autoload();


Of course, the above is just the simplest demonstration. __autoload just goes to include_path to find the class file and loads it. We can define the rules for __autoload to load classes according to our own needs.

In addition, if we do not want to call __autoload when automatically loading, but call our own function (or class method), we can use spl_autoload_register to register our own autoload function. Its function prototype is as follows:
bool spl_autoload_register ([callback $autoload_function] )

Let’s continue to rewrite the above example:

The code is as follows Copy code
 代码如下 复制代码

view plaincopy to clipboardprint?
function loader($class)  
{  
$file = $class . '.php';  
if (is_file($file)) {  
require_once($file);  
}  
}  

spl_autoload_register('loader');  

$a = new A();

function loader($class)
{
$file = $class . '.php';
if (is_file($file)) {
require_once($file);
}
}

spl_autoload_register('loader');

$a = new A();

view plaincopy to clipboardprint?

function loader($class)

{
 代码如下 复制代码

view plaincopy to clipboardprint?
class Loader  
{  
public static function loadClass($class)  
{  
$file = $class . '.php';  
if (is_file($file)) {  
require_once($file);  
}  
}  
}  

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

$a = new A();

$file = $class . '.php';
if (is_file($file)) { require_once($file);

}

} spl_autoload_register('loader'); $a = new A(); function loader($class) { $file = $class . '.php'; if (is_file($file)) { require_once($file); } }
spl_autoload_register('loader');
$a = new A();
This can also run normally. At this time, when PHP is looking for a class, it does not call __autoload but calls our own defined function loader. For the same reason, the following writing method is also possible:
The code is as follows Copy code
view plaincopy to clipboardprint? class Loader { public static function loadClass($class) { $file = $class . '.php'; if (is_file($file)) { require_once($file); } } } spl_autoload_register(array('Loader', 'loadClass')); $a = new A();
http://www.bkjia.com/PHPjc/445632.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/445632.htmlTechArticleIn php, the spl_autoload_register and __autoload methods are only available in php5. Let me introduce these two magic tricks to you. You can learn more about how to use the function. spl_autoload_reg...
Statement:
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