Home  >  Article  >  php教程  >  php基础知识:类与对象(2) 自动加载对象

php基础知识:类与对象(2) 自动加载对象

WBOY
WBOYOriginal
2016-06-13 12:35:141033browse

自动加载对象:
   很多开发者写面向对象的应用程序时对每个类的定义建立一个 PHP 源文件。一个很大的烦恼是不得不在每个脚本(每个类一个文件)开头写一个长长的包含文件列表。 
   在 PHP 5 中,不再需要这样了。可以定义一个 __autoload 函数,它会在试图使用尚未被定义的类时自动调用。通过调用此函数,脚本引擎在 PHP 出错失败前有了最后一个机会加载所需的类。 

本例尝试分别从 MyClass1.php 和 MyClass2.php 文件中加载 MyClass1 和 MyClass2 类。 
function __autoload($class_name) {
   require_once $class_name . '.php';
}
$obj  = new MyClass1();
$obj2 = new MyClass2();
注意: 
在 __autoload 函数中抛出的异常不能被 catch 语句块捕获并导致致命错误。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn