phoenixfox
(phoenixfox)
中级会员
 
中级会员
UID 67568
精华
0
积分 289
帖子 240
金钱 289 喜悦币
威望 0
人脉 0
阅读权限 30
注册 2005-12-28
状态 离线
|
[广告]: q
m
给小菜说说_autoload的用法
首先有必要讲述PHP5的一个对象
Autoloading Objects,
手册中是这样介绍的
Many developers writing object-oriented applications create one PHP source file per-class definition. One of the biggest annoyances is having to write a long list of needed includes at the beginning of each script (one for each class).
In PHP 5, this is no longer necessary. You may define an __autoload function which is automatically called in case you are trying to use a class which hasn't been defined yet. By calling this function the scripting engine is given a last chance to load the class before PHP fails with an error.
Note: Exceptions thrown in __autoload function cannot be caught in the catch block and results in a fatal error.
Note: Autoloading is not available if using PHP in CLI interactive mode.
我翻译的(可能不十分标准,说下大概意思):
许多应用PHP与面向对象思量来结合开发时,当他写一个php脚本时对于每一个类文件的定义都要明确,也就是说在每个脚本中你必须要有大量的includes require这样的代码。
(现在一般的解决办法是在一个公用的文件中包含系统将要包含的所有文件,然后再通过包含这个文件这样来实现的)
在PHP5中,你将会有一种新的方式来解决这个问题,那就是__autoload,你可以定义__autoload这样一个函数在你的脚本中,当你的一个类名还没有被定义的时候,编译器会自动的执行该函数。而这个函数会在系统报出类名未定义前,给你一个加载文件的机会。
注意:在这个函数中的错误是不能被错误机制所扑获的,他会直接给出一个致命错误。
如果php是在CLI(命令行界面)交互模式下,该函数是不可用的。(问了一下高人说是在DOS命令那中执行方式时是不成的 {就是那种cmd,然后php.exe那种模式是不行的}不知道对不对。等其他大人详解)
例:
<?php
function __autoload($class_name) {
require_once $class_name . '.php';
}
$obj = new MyClass1();
$obj2 = new MyClass2();
?>
这个例子就说明了 在你执行实例化时候如果类名还未定义,你有一次机会先将类包含进来,从而实现了类的动态加载。在实际应用当中是非常有用的。
如:
你在构造系统目录结构与类名的关系时,你可以采用一个固定的模式
例:classes目录 用来存放各种类
如果下面还有子目录时,你可以在定义类的时候用子目录名+_+你想用的类名来重构你的类名。而文件名则用你想用的类名+.php即可
function __autoload($class)
{
$file = str_replace('_','/',$class).'.php';
require_once(REAL_PATH.'classes/'.$file);
}
这样通过上面的函数你就可以加载任何你已经写好的类了,而不用在文件前写大量的require_once(’…….’)这样的代码了
|
|