Parsing php class registration and automatic loading
Source: Internet
Author: User
This article provides a detailed analysis of php class registration and automatic loading. For more information, see
The project directory is as follows:
1. Place the classes 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. 'ing ing/UserMapper. php ',
);
Return $ classes;
}
}
?>
2. register an array Note:The class paths in step 1 are relative to init. php, not to Utils, because we use the automatic loading function spl_autoload_register in init. php to require the class.
The code is as follows:
Require_once '/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 is used. The code is as follows:
Require_once 'init. php ';
$ Dao = new UserDao ();
$ Result = $ dao-> findByName ('zcl ');
?>
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.