Home  >  Article  >  Backend Development  >  Basic knowledge of PHP: Classes and objects (2) Automatically loading objects_PHP tutorial

Basic knowledge of PHP: Classes and objects (2) Automatically loading objects_PHP tutorial

WBOY
WBOYOriginal
2016-07-21 15:59:15732browse

Automatically load objects:
Many developers create a PHP source file for each class definition when writing object-oriented applications. A big annoyance is having to write a long list of include files at the beginning of each script (one file per class).
In PHP 5, this is no longer necessary. You can define an __autoload function that will be automatically called when trying to use a class that has not yet been defined. By calling this function, the scripting engine has a last chance to load the required classes before PHP fails with an error.

This example attempts to load the MyClass1 and MyClass2 classes from the MyClass1.php and MyClass2.php files respectively.
function __autoload($class_name) {
require_once $class_name . '.php';
}
$obj = new MyClass1();
$obj2 = new MyClass2();
Note:
Exceptions thrown in the __autoload function cannot be caught by the catch statement block and result in a fatal error.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/317408.htmlTechArticleAutomatic loading of objects: Many developers create a PHP source for each class definition when writing object-oriented applications. document. A big annoyance is having to do this in every script (one text per class...
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