The content of this article is about the automatic loading of PHP classes. It has a certain reference value. Now I share it with everyone. Friends in need can refer to it.
Write a HumanModel.php## first. #
class HumanModel { public function t() { echo '人类<br >'; } }
// =Example= //
require('./HumanModel.php');$lisi = new HumanModel();$lisi->t(); // 人类
// =Automatic loading of classes= //
function __autoload($c) { echo '~~~~~~~~~',$c,'~~~~~~~~'; }$ming = new Dog();
// === Notes Part 1===
Automatic loading of classes
Before reporting an error, we can also use the __autoload function
Get an intervention opportunity
and automatically pass the "class name" to the __autoload function
*/
function __autoload($c) { echo '我先自动加载'; echo './' . $c . '.php'; echo '<br >'; require('./' . $c . '.php'); }$lisi = new HumanModel();$lisi->t();// 我先自动加载./HumanModel.php// 人类function test() { // 函数内可以写任何合法的PHP代码,包含再声明一个函数/类 class Bird { public static function sing() { echo '百灵鸟放声歌唱!<br >'; } } }// 必须要调用函数然后才能执行内部test(); Bird::sing(); /* Bird::sing(); 未定义类 转到上面类的自动加载函数中,于是报错如下: Warning: require(./Bird.php): failed to open stream: No such file or directory 找不到Bird这个php */
// ===Notes Part 2===
Can automatic loading only use the __autoload function?
Answer: No, in fact, you can also specify a function.
Use the system function spl_autoload_register to notify
*/
spl_autoload_register('zidongjiazai');function zidongjiazai($c) { require('./' . $c . '.php'); }$HumanModel = new HumanModel();$HumanModel->t();
class HumanModel { public function t() { echo '人类<br >'; } }
// =Example= //
require('./HumanModel.php');$lisi = new HumanModel();$lisi->t(); // 人类
// =Automatic loading of classes= //
function __autoload($c) { echo '~~~~~~~~~',$c,'~~~~~~~~'; }$ming = new Dog();
// ===Notes Part 1===
Automatic loading of classes
Before reporting an error, we can also use the __autoload function
Get an intervention opportunity
and automatically pass the "class name" to the __autoload function
*/
function __autoload($c) { echo '我先自动加载'; echo './' . $c . '.php'; echo '<br >'; require('./' . $c . '.php'); }$lisi = new HumanModel();$lisi->t();// 我先自动加载./HumanModel.php// 人类function test() { // 函数内可以写任何合法的PHP代码,包含再声明一个函数/类 class Bird { public static function sing() { echo '百灵鸟放声歌唱!<br >'; } } }// 必须要调用函数然后才能执行内部test(); Bird::sing(); /* Bird::sing(); 未定义类 转到上面类的自动加载函数中,于是报错如下: Warning: require(./Bird.php): failed to open stream: No such file or directory 找不到Bird这个php */
// ===Notes Part 2===
Can automatic loading only use the __autoload function?
Answer: No, in fact, you can also specify a function.
Use the system function spl_autoload_register to notify
*/
spl_autoload_register('zidongjiazai');function zidongjiazai($c) { require('./' . $c . '.php'); }$HumanModel = new HumanModel();$HumanModel->t();
The above is the detailed content of Automatic loading of PHP classes. For more information, please follow other related articles on the PHP Chinese website!