spl_autoload_register and __autoload () magic method

Prior to PHP 5.3, __ autoload function throws exception catch block that can not be captured and can cause a fatal error (Fatal Error). 

Although the __autoload () function can be automatically loaded classes and interfaces, but more recommended spl_autoload_register () function. spl_autoload_register () provides a more flexible way to automatically load class (the same application can support any number of loaders, such as third-party library). Therefore, no longer recommended __autoload () function, in future releases it may be abandoned.

autoload_function
This method is a function of [name], it can be a string or array (class method calls). Of this function (method) is to the needs of the new class file contains include (requeire) come in, so when he does not find the new files. In fact, include and require functions encapsulate the entire project.

throw
This parameter sets can not be registered when autoload_function success, spl_autoload_register () if an exception is thrown.

prepend
If true, spl_autoload_register () function will be added to the head of the queue, rather than the tail of the queue.

test.php

<?php
class test
{
    function __construct(){
        echo " the Test class is initialized <br> " ;
    }
    function show(){
        // current page is utf8 encoding    
        $ str = ' Chinese 89PHP ' ;

        strlen echo (STR $). " a " ; // Chinese + + number English:. 6 + 2 = +. 11. 3 
        echo mb_strlen (STR $, ' GBK ' ). " a " ; // Chinese English + number +: + 3 + 2 = 3. 8 
        echo mb_strlen (STR $, ' UTF8 ' ). " a " ; // Chinese + + number English: 2 + 2 + 3 = 7

        // database varchar a Chinese account for a character length 
    }
}
my_autoload.php file
<? PHP
 // Method One: After the automatic loading function deprecated 5.0 
/ * function __autoload ($ class)
{
    $file = $class . '.php';
    if ( is_file($file) ) {
        require_once($file);
    }
}

$ Test = new test (); // Output: test class is initialized
*/

// use spl_autoload_register function
 // Method two: 
class my_autoload
{
    public static function autoload($class){
        $file = $class . '.php';
        if ( is_file($file) ) {
            require_once($file);
        }
    }
}
// Register loading 
spl_autoload_register ( " my_autoload :: the autoload " , to true , to true );

Test $ = new new Test (); // Output: test class is initialized 
$ Test-> Show ();

?>

 

Guess you like

Origin www.cnblogs.com/wanglijun/p/10926499.html