PHP Object-oriented strategy (17) Automatic Loading class _php Foundation

Source: Internet
Author: User
Auto Load Class
Many developers write object-oriented applications, creating a PHP source file for each class definition. A very large
The trouble is having to write a long list of included files at the beginning of each script (one file per class).
In a software development system, it is not possible to write all classes in a PHP file, when in a PHP file
When you need to invoke a class declared in another file, you need to introduce the file through include. But sometimes,
In a large number of documents, it is a very frustrating thing to include all of the required class files in the project, so
Can we import the PHP file of this class when we use the class? That's what we're here for.
The automatic load class to talk about.
In PHP5, you can define a __autoload () function that will automatically tune when you try to use a class that has not yet been defined
With, by calling this function, the script engine has the last chance to load the required class before the PHP error fails.
The __autoload () function receives a parameter that is the class name of the class you want to load, so when you do the project, the organization defines
class file name, you need to follow certain rules, preferably with the class name as the center, or with a uniform prefix or suffix shape
File names, such as xxx_classname.php, classname_xxx.php, and classname.php, and so on.
This example attempts to load the MYCLASS1 and MYCLASS2 classes separately from the myclass1.php and myclass2.php files
Code fragment
Copy Code code as follows:

<?php
function __autoload ($classname) {
Require_once $classname. '. php ';
}
The MyClass1 class does not have an automatic call to the __autoload () function, passing in the argument "MyClass1"
$obj = new MyClass1 ();
The MyClass2 class does not have an automatic call to the __autoload () function, passing in the argument "MyClass2"
$obj 2 = new MyClass2 ();
?>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.