在PHP中实现自动加载功能,通常使用魔术方法__autoload()或spl_autoload_register()函数。
方法一:使用__autoload()方法
```php
function __autoload($class) {
require_once "$class.php";
}
$obj = new MyClass();
```
方法二:使用spl_autoload_register()函数
```php
spl_autoload_register(function ($class) {
require_once "$class.php";
});
$obj = new MyClass();
```
这两种方法都会在需要使用某个类时自动加载该类文件,无需手动require或include。需要注意的是,__autoload()方法在PHP7.2已经被废弃,推荐使用spl_autoload_register()函数实现自动加载功能。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: php try catch使用无效怎么解决