PHP Automatic loading class __autoload () function use method

Source: Internet
Author: User
Tags autoload
When developing object-oriented applications in PHP, it is often necessary to invoke a variety of class libraries, so that the class libraries are referenced by require or include when using them. Now the __autoload () function can give us a lot of convenience.

In PHP 5, you can define a __autoload () function that will be called automatically when trying to use a class that has not yet been defined, and by calling this function, the scripting engine has a last chance to load the required class before PHP fails, and a parameter that the __autoload () function receives. is the class name of the class you want to load, so when you do the project, when the organization defines the name of the class, you need to follow certain rules, preferably with the class name as the center, or a uniform prefix or suffix to form the file name, such as xxx_classname.php, classname_ Xxx.php and is classname.php and so on.

This example attempts to load the MyClass1 and MyClass2 classes from the myclass1.php and myclass2.php files, respectively

  
   
function __autoload ($classname)
{
Require_once $classname. '. php ';
}

When the MyClass1 class does not exist, the __autoload () function is called automatically, passing in the parameter "MyClass1"
$obj = new MyClass1 ();

When the MyClass2 class does not exist, the __autoload () function is called automatically, passing in the parameter "MyClass2"
$obj 2 = new MyClass2 ();

?>

We can use the following processing methods in our program:

  
   
if (function_exists (' Spl_autoload_register '))
{
Spl_autoload_register (Array (' core ', ' autoload '));
}
Else
{
function __autoload ($class)
{
Return Core::autoload ($class);
}

Note: __autoload () is specifically designed for the non-existence of the Class!!! Many frameworks use this function to implement automatic loading of class files!!!

  • 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.