PHP-based Autoload. The autoload mechanism of PHP is very important. here we will make two original articles on small exercises. For more information, see www. cnblogs. the comphpgcs file structure is as follows. two methods are used to automatically load 1. the PHP autoload mechanism is very important. here we will do two small exercises.
Original article, reproduced please note: http://www.cnblogs.com/phpgcs
The file structure is as follows, which can be automatically loaded in two ways
1. user-defined functions
2, spl_autoload_register ()
Liuyuan @ ebuinfo:/var/www/phpgcs/php_autoload $ ll ./*
-Rw-r -- 1 liuyuan 800 Feb 19 :39./func_autoload.php
-Rw-r -- 1 liuyuan 906 Feb 19 :28./spl_autoload.php
./Include:
Total 16
Drwxrwxr-x 2 liuyuan 4096 Feb 19 11: 42 ./
Drwxrwxr-x 3 liuyuan 4096 Feb 19 11: 43 ../
-Rw-r -- 1 liuyuan 142 Feb 19 :42 aClass. php
-Rw-r -- 1 liuyuan 143 Feb 19 :42 bClass. php
First, let's look at the custom function method:
Define ('eol ', (PHP_SAPI = 'cli ')? PHP_EOL :' ');
Print_r (get_included_files ());
Echo EOL;
Print get_include_path ();
Echo EOL;
// Set_include_path (get_include_path (). PATH_SEPARATOR. '/var/www/ly_php/php_spl/include /');
// Set_include_path (dirname (_ FILE _). '/include ');
// Set_include_path (dirname (_ FILE _). '/include /');
Function _ autoload ($ className ){
$ Filename = './include/'. $ className. '. php ';
// $ Filename = './include/'. $ className. '. php ';
// $ Filename = '/var/www/ly_php/php_spl/include/'. $ className. '. php ';
If (file_exists ($ filename )){
Include_once $ filename;
} Else {
Exit ('No file ');
}
}
$ A = new aClass ();
$ B = new bClass ();
Print_r (get_included_files ());
?>
The running result is as follows:
+ View Code
Method 2:
Class myLoader {
Public static function autoload ($ className ){
$ Filename = './include/'. $ className. '. php ';
If (file_exists ($ filename )){
Include_once $ filename;
} Else {
Exit ('No file ');
}
}
}
Define ('eol ', (PHP_SAPI = 'cli ')? PHP_EOL :'
');
Spl_autoload_register (array ('myload', 'autoload '));
/**
* The _ autoload method will expire after spl_autoload_register, because the autoload_func function pointer has pointed to the spl_autoload method
* You can add the _ autoload method to the autoload_functions list using the following method:
*/
// Spl_autoload_register ('_ autoload ');
Error_reporting (E_ALL ^ E_NOTICE ^ E_WARNING ^ E_ERROR );
Error_reporting (E_NOTICE | E_WARNING );
$ A = new aClass ();
Print_r (get_included_files ());
Echo EOL;
$ B = new bClass ();
Echo EOL;
?>
Original article, reprint please note: http://www.cnblogs.com/phpgcs file structure is as follows, 2 ways to achieve automatic loading 1 ,...