Registration and automatic loading of php classes__autoload_PHP tutorial

WBOY
Release: 2016-07-13 16:56:51
Original
844 people have browsed it

__autoload() is a function agreed in the PHP execution environment rather than a method of a certain class. If a class is not loaded into the current file before use, the __autoload() function will be automatically called to load the class. Usually these The loading rules of classes are agreed upon. For example, these classes are included in files named after the class names. This method can realize on-demand loading of classes and avoid loading unnecessary classes before script execution, thereby reducing resource usage and submission performance.

Note: Errors within __autoload() cannot be caught by try-catch.

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

function __autoload($class_name){

     require_once(PATH.'/calsses/'.$class_name.'.php');

}

$obj1 = new mycalss1();

function __autoload($class_name){

require_once(PATH.'/calsses/'.$class_name.'.php');

}

$obj1 = new mycalss1();

Register the function automatically called by __autoload():
 代码如下 复制代码

spl_autoload_register(array('class_name'|$obj,'method_name'));

例如:

spl_autoload_register(array($this,'autoloadClass'));

The spl code base is automatically enabled by default after PHP5.0

spl_autoload_register([callback]); //Instead of writing the specific loading code in __autoload(), you can use this function to register the callback function.

If you use a class method as a callback function, you need to pass in an array:

The code is as follows Copy code

spl_autoload_register(array('class_name'|$obj,'method_name'));

For example:

spl_autoload_register(array($this,'autoloadClass'));

spl_autoload_register(array('YiiBase','autoload'));//Implementation of the autoloading class of the YII framework, the YiiBase class implements an autoload method. spl_autoload_register() can register multiple load functions, and all registered load functions will be tried one by one before successfully loading the class file. This is useful when different classes use different logic to import class files.

spl_autoload_unregister(); //Cancel a registered load function, the parameters are the same as spl_autoload_register().

 代码如下 复制代码

spl_autoload_extentions(".class.php");

spl_autoload_register(); //使用spl_autoload() 来尝试自动加载类文件

//这样 spl_autoload('myclassName'); 会尝试加载 文件 "myclassName.class.php" .

spl_autoload_functions();// Returns all registered __autoload() functions in array form spl_autoload(class_name[,file_extentions]); //Default implementation of __autoload() function. If no function name is passed in when spl_autoload_register() is called, this function will be used by default. The execution rules of this function are: The class name is converted to lowercase as the file name, and the passed-in file_extensions (multiple extensions are separated by commas, default (.inc and .php) as the extension, try to search in the include paths set in php.ini based on the file name obtained. spl_autoload_call(class_name);//Manually call all registered __autoload() functions to actively load class files spl_autoload_extensions([file_extensions]); //Register or return the file extensions that can be used in spl_autoload(). The extension can be in the form of .a.b, for example:
The code is as follows Copy code
spl_autoload_extensions(".class.php"); spl_autoload_register(); //Use spl_autoload() to try to automatically load class files //In this way spl_autoload('myclassName'); will try to load the file "myclassName.class.php" .

Example

1. Put the classes that need to be registered in an array

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


final class Utils {

private function __construct() {

}

public static function getClasses($pre_path = '/') {
$classes = array(
'DBConfig' => $pre_path.'DBConfig/DBConfig.php',
                'User' => $pre_path.'Model/User.php',
                'Dao' => $pre_path.'Dao/Dao.php',
                'UserDao' => $pre_path.'Dao/UserDao.php',
                'UserMapper' => $pre_path.'Mapping/UserMapper.php',
        );
        return $classes;
    }
}
?>

Copy code


final class Utils {

代码如下 复制代码


require_once '/Utils/Utils.php';
final class Init {

/**
* System config.
*/
public function init() {
// error reporting - all errors for development (ensure you have
// display_errors = On in your php.ini file)
error_reporting ( E_ALL | E_STRICT );
mb_internal_encoding ( 'UTF-8' );
//registe classes
spl_autoload_register ( array ($this,'loadClass' ) );
}

/**
* Class loader.
*/
public function loadClass($name) {
$classes = Utils::getClasses ();
if (! array_key_exists ( $name, $classes )) {
die ( 'Class "' . $name . '" not found.' );
}
require_once $classes [$name];
}
}
$init = new Init ();
$init->init ();
?>

private function __construct() {

}

public static function getClasses($pre_path = '/') {
         $classes = array(
               'DBConfig' => $pre_path.'DBConfig/DBConfig.php',
                 'User' => $pre_path.'Model/User.php',
                'Dao' => $pre_path.'Dao/Dao.php',
                'UserDao' => $pre_path.'Dao/UserDao.php',
                'UserMapper' => $pre_path.'Mapping/UserMapper.php',
);
          return $classes;
}
}
?>
 代码如下 复制代码

require_once 'Init.php';

$dao = new UserDao();
$result = $dao->findByName('zcl');
?>

2. Registration array Note: The paths of the classes in step 1 are relative to init.php, not relative to Utils. This is because we require the class through the autoloading function spl_autoload_register in init.php
The code is as follows Copy code

require_once '/Utils/Utils.php';
final class Init {

/**
     * System config.
    */
Public function init() {
// error reporting - all errors for development (ensure you have
// display_errors = On in your php.ini file)
        error_reporting ( E_ALL | E_STRICT );
         mb_internal_encoding ( 'UTF-8' );
           //registe classes
spl_autoload_register ( array ($this,'loadClass' ) );
}

/**
     * Class loader.
    */
Public function loadClass($name) {
         $classes = Utils::getClasses ();
If (! array_key_exists ( $name, $classes )) {
                  die ( 'Class "' . $name . '" not found.' );
         }
          require_once $classes [$name];
}
}
$init = new Init ();
$init->init ();
?> 3. In this example, require init.php in test.php where it is used
The code is as follows Copy code
require_once 'Init.php';<🎜> <🎜>$dao = new UserDao();
$result = $dao->findByName('zcl');
?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/631580.htmlTechArticle__autoload() is a function agreed in the PHP execution environment rather than a method of a certain class. If a class is in If it has not been loaded into the current file before use, the __autoload() function will be automatically called to add...
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!