php面向对象全攻略 (十七) 自动加载类
自动加载类
很多开发者写面向对象的应用程序时,对每个类的定义建立一个PHP 源文件。一个很大
的烦恼是不得不在每个脚本(每个类一个文件)开头写一个长长的包含文件的列表。
在软件开发的系统中,不可能把所有的类都写在一个PHP 文件中,当在一个PHP 文件
中需要调用另一个文件中声明的类时,就需要通过include 把这个文件引入。不过有的时候,
在文件众多的项目中,要一一将所需类的文件都include 进来,是一个很让人头疼的事,所以
我们能不能在用到什么类的时候,再把这个类所在的PHP 文件导入呢?这就是我们这里我们
要讲的自动加载类。
在PHP5 中,可以定义一个__autoload()函数,它会在试图使用尚未被定义的类时自动调
用,通过调用此函数,脚本引擎在PHP 出错失败前有了最后一个机会加载所需的类,
__autoload()函数接收的一个参数,就是你想加载的类的类名,所以你做项目时,在组织定义
类的文件名时,需要按照一定的规则,最好以类名为中心,也可以加上统一的前缀或后缀形
成文件名,比如xxx_classname.php、classname_xxx.php 以及就是classname.php 等等。
本例尝试分别从MyClass1.php 和MyClass2.php 文件中加载MyClass1 和MyClass2 类
代码片段
复制代码 代码如下:
function __autoload($classname) {
require_once $classname . '.php';
}
//MyClass1类不存在自动调用__autoload()函数,传入参数”MyClass1”
$obj = new MyClass1();
//MyClass2类不存在自动调用__autoload()函数,传入参数”MyClass2”
$obj2 = new MyClass2();
?>

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver CS6
Visual web development tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Atom editor mac version download
The most popular open source editor

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.
