PHP class automatic loading method, PHP Loading Method

Source: Internet
Author: User

PHP class automatic loading method, PHP Loading Method

Automatic class loading means that you do not need to "introduce" class files on the external page, but the program will dynamically load the required class files as needed.

Method 1: Use the _ autoload magic Function

When a program needs a class, it will call this function. We need to define this function and write the general statements for loading class files.

<? Php // The required class is automatically called and a class name will be passed in. In this case, the file name is 21A. class. php, Class Name: A function _ autoload ($ className) {require ". /21 ". $ className. ". class. php ";}$ o1 = new A (); $ o1-> v1 = 10; echo" <br/> v1 :". $ o1-> v1;?>

Method 2:Use the spl_autoload_register Function

The function functions multiple functions that can be used to replace the autoload function. The syntax is as follows: spl_autoload_regist ("function name 1"); If spl_autoload_register is used, autoload becomes invalid.

<? Php // register two function names for automatic loading: spl_autoload_register ('auto1'); spl_autoload_register ('auto2'); function auto1 ($ className) {$ file = ". /21 ". $ className. ". class. php "; if (file_exists ($ file) {require ". /21 ". $ className. ". class. php ";}} function auto1 ($ className) {$ file = ". /22 ". $ className. ". class. php "; if (file_exists ($ file) {require ". /22 ". $ className. ". class. php ";}}// if a ray is required, but this page has not been recorded, it will call auto1 and auto2 in turn, knowing to find this Class file and load?>

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

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.