<?php
//Demo.class.php文件内容
class Demo
{
public $desc;
public function __construct($desc='php中文网')
{
$this->desc = $desc;
}
}
?>
<?php
//第一种方法 使用autoload系统函数
// function __autoload($className){
// $file = $className.'.class.php';
// if(file_exists($file)){
// require_once($file);
// }else{
// echo '请检查文件是否存在~~';
// }
// }
//第二种方法 使用spl_autoload_register()函数
// function loader($className){
// $file = $className.'.class.php';
// if(file_exists($file)){
// require_once($file);
// }else{
// echo '请检查文件是否存在~~';
// }
// }
// spl_autoload_register('loader');
//第三种方法 把自动加载函数放在一个类里面
class Loader
{
public static function loaderFunc($className){
$file = $className.'.class.php';
if(file_exists($file)){
require_once($file);
}else{
echo '请检查文件是否存在~~';
}
}
}
spl_autoload_register([(new Loader),'loaderFunc']);//如果loaderFunc是静态方法,那么可以这样写spl_autoload_register(['Loader','loaderFunc']);
$obj = new Demo('我爱php');
echo $obj->desc;
?>点击 "运行实例" 按钮查看在线实例
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号