PHP Learning-Automatic loading of classes

Source: Internet
Author: User

In fact, I also do not understand what is the use of automatic loading of classes, only to record the learning process.

1. Using the __autoload ($className) method

For example, there is an external class that we need to read in another PHP file, which can usually be loaded using the __autoload method.

For example:

There is a person class:

1 <? PHP 2 class person{3     4 }

We construct the object of this person class in another PHP file.

1 function __autoload ($className) {2     require$className . ". php"; 3 }45$personnew person (); 6 Var_dump ($person);

It is important to note that the file name must be the same as the class name.

2. Using the Spl_autoload_register ($className) method

A. Passing an anonymous function (closure)

Spl_autoload_register (function($className) {    require$className . ". php";});

B. One way to pass a class

1<?PHP2 3 classbean{4      Public functionAutoLoad ($className){5         require $className. ". php";6     }7 }8 9 /**Ten * The first parameter is the object of a class One * The second parameter is a method in the class A   */ -Spl_autoload_register ([NewBean, ' AutoLoad ']); - $person=NewPerson (); the Var_dump($person);

PHP Learning-Automatic loading of classes

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.