php自动加载类示例
本例有三个文件,app.php、Student.class.php 和Teacher.cla.php,两个类文件分别在public 和 libs文件夹,其目录结构如下图:

<?php header("Content-type: text/html; charset=utf-8"); //设置中国时区 date_default_timezone_set('PRC'); //注册函数 spl_autoload_register("func1"); spl_autoload_register("func2"); // __autoload("func2"); // require("./public/Student.class.php"); function func1($className) { $filename = "./public/$className.class.php"; if (file_exists($filename)) require_once($filename); } function func2($className) { $filename = "./libs/$className.cla.php"; if (file_exists($filename)) require_once($filename); } $obj1 = new Student(); $obj2 = new Teacher();
Student.class.php位于Teacher文件夹,内容如下:
<?php class Student { private $name = "Tom"; private $age = 24; public function __construct(){ echo "{$this->name}的年龄是{$this->age}岁。<br>"; } }
Teacher.cla.php位于libs文件夹,内容如下:
<?php class Teacher { private $name = "Mr Liu"; private $school = "北京科技大学"; public function __construct(){ echo "{$this->name}毕业于{$this->school}"; } }

浙公网安备 33010602011771号