How classes are loaded automatically in PHP

Source: Internet
Author: User
Tags autoload spl php class
This article mainly introduces the method of automatic loading in PHP, has a certain reference value, now share to everyone, the need for friends can refer to

Recently in the study of composer, found that from the touch of PHP to now have encountered three kinds of PHP in the automatic loading of classes, including the PHP self-contained classes of the automatic loading mode, PHP's third-party dependency management tool composer The way it is loaded and automatically loaded under PHP's YAF framework. This blog is mainly for the PHP5 of the loading method to carry out a detailed introduction, composer and Yaf under the class of automatic loading will be in the next time two articles and learn together.

1. Manual load Mode

  In languages like C and C + +, when you need to use related classes or methods in another file in PHP, you can use include, include_once, require, or require_once to include the files in the project. Among them, the four differences are as follows.

    • Include will apply a file, if the file does not exist, give a hint, skip continue execution;

    • Include_once also applies a file, but only once, if the file does not exist, continue execution;

    • Require indicates that a file is applied, and if the file does not exist, the execution of the program is interrupted;

    • Require_once also applies a file, and only applies once, if the file does not exist, then interrupt the execution of the program;

The above four ways are required files, manually included in the program files. This is possible when the size of the project is small, but as the size of the project expands, the classes needed to load each file manually are a nightmare.

For the sake of convenience, the load path can be set by Set_include_path () at load time, and the loaded path can also be obtained by Get_include_path (). With regard to Set_include_path () and Get_include_path (), I was just in touch, here only a brief introduction to Set_include_path (), and then add to the problems encountered later.

First, Set_include_path () is dynamically modifying the include_path in the php.ini in the script, and this include_path is for include and require (if not specifically described later in this article, The include represents the path for include and Include_once,require on behalf of require and require_once), or is predefined. If we need to use the a.php, b.php, c.php in a main.php file in the Projname/home/lib/mylib/test folder, if there is no path to include, write the following form:

<? PHP        include ("projname/home/lib/mylib/test/a.php");        Include ("projname/home/lib/mylib/test/b.php");        Include ("projname/home/lib/mylib/test/c.php");  ......

This makes it cumbersome to include an absolute path for each include. If you add Set_include_path ("Projname/home/lib/mylib/test") before the files that need to be included, you can write in the following form:

<? PHP    Set_include_path ("Projname/home/lib/mylib/test");    Include ("a.php");    Include ("b.php");    Include ("c.php");    ......

The second obviously saves a lot of time compared to the first laborious way of writing, but it's still a matter of containing each file, just simplifying the included path. Of course, the above-mentioned situation is that the required files exist in a folder, if the file exists in a different folder, then you can add multiple set_include_path () statements, At this point, if the files in include or require contain filenames that appear in multiple directories, only the files that appear first in the Set_include_path directory will be included, and if none of the Set_include_path specified folders have corresponding files, The file name exactly appears in the current folder, and it directly contains the corresponding files in the current directory.

The Get_include_path () function is only available for getting the current include path.

  2._autoload and Spl_autoload_register () Auto Load mode

In order to free the hands from the loading mode of the class, an automatic loading mechanism is provided in PHP5 and later versions---autoload. AutoLoad allows classes to be loaded only when they are actually needed, that is, the so-called lazy loading, rather than starting with the include or require all class files. The automatic loading mechanism provided by PHP is divided into two types---__autoload () and Spl_autoload_register ().

  1). __autoload mechanism

  In the process of running a program in PHP5, if you find that a class is not included, you will run the __autoload auto-load mechanism to load the required classes. The wording is as follows:

<? Phppublic function  __autoload ($classname) {$fileName = $classname. " PHP ";" if (File_exist ($fileName)) {require_once ("$fileName");} else {echo $fileName. "Doesn ' t exist!"}}

According to this procedure, we can get the following conclusion: the principle of guaranteeing the automatic loading mechanism is to make the class name and file name have a correspondence relation, and the class name + suffix forms the name of the file where the class resides. If this file does exist, then the class is loaded into it according to $filename. If the file does not exist, the user is prompted and the file does not exist. In general, the automatic loading mechanism consists of three steps:

    • The file name is determined according to the class name, which is a uniform correspondence rule between the class name and the file name.

    • Find corresponding files on disk according to the file name (the simplest case is that the class is in the same directory as the PHP file that called them); if it is not in the same directory, you can use Set_include_path () to specify the path to load;

    • Load the disk file into the file system, this step only contains the corresponding class file with the general include and require;

__autoload () The principle of implementing the automatic loading of classes is that there is a uniform correspondence between the class name and the file name, which is the key to implement __autoload in a system. However, a system may be developed by different people, if there is no agreed standard before development, there may be different corresponding rules, resulting in the need to implement a variety of load rules in __autoload (), it may lead to the __autoload () function is very bloated. To solve this problem, PHP also provides an automatic loading mechanism---spl_autoload_register ().

  2). Spl_autoload_register () mechanism

SPL is the abbreviation for standard PHP Library (PHP), an extension library introduced by PHP5. SPL AutoLoad is implemented by pointing the function pointer autoload_func to the auto-mount function. SPL has two different auto-loading functions, spl_autoload and Spl_autoload_call, which enable different automatic loading mechanisms by pointing autoload_fun to these two different load function addresses.

    • Spl_autoload

Spl_autoload is the default auto-load function implemented by SPL and is a function that can accept two parameters. The first function is $class_name, which represents the class name to load, and the second argument is $file_extension as an optional parameter that represents the extension of the class file. You can specify multiple extensions in the $file _extension, separated by semicolons, with no extension specified, using the default extension. inc or. php. Spl_autoload first turns $class_name into lowercase, and then searches for $ class_name.inc or $class_name.php files in all include_path. If the corresponding file is found, the corresponding class is loaded. In fact, you can manually use the Spl_autoload ("xxxx", ". php") to implement the XXXX class loading. This is actually similar to Require/include, but Spl_autoload is relatively flexible because multiple extensions can be specified.

As mentioned earlier, the function pointer contained in Spl_autoload_register AUTOLOAD_FUNC is used to specify the load function to use. Then, we must assign the corresponding function address to Autoload_func,spl_autoload_register () is implementing the function pointer Autoload_func assignment. If the Spl_autoload_register () function does not contain any parameters, the default is to assign the Spl_autoload () value to Autoload_func.

    • Spl_autoload_call

There is actually a autoload_functions inside the SPL module, which is essentially a hash table, or, for intuitive understanding, we think of it as a container in which each element is a pointer to the loaded function. Spl_autoload_call Implementation mechanism is also relatively simple, in a certain order to traverse the container, execute the function pointer inside the load function, each execution of a pointer will check whether the required class has finished loading. If the load is completed, exit. Otherwise, continue to execute down. If all the loaded functions are executed, the required classes still do not finish loading, then Spl_autoload_call () exits directly. This means that even if the autoload mechanism is used, it is not always possible to complete the loading of classes, the key is to see how you create your auto-load function.

Now that there is a autoload_functions, how do you add the auto-load function you created to it? Spl_autoload, the load function is also registered to autoload_functions using Spl_autoload_register (). Of course, you can remove the registered function from the hash table from Autoload_functions by using the Spl_autoload_unregister () function.

One thing to note here is the order in which Spl_autoload_register implements automatic loading. Spl_autoload Automatic loading order is: first determine whether the Autoload_func is empty, if the Autoload_func is empty, then see if the __autoload function is defined, if not defined, then return, and error, if you define __ The AutoLoad () function returns the loaded result. If Autoload_func is not empty, the function that the Autoload_func pointer points to is executed directly, and the __autoload is not checked for definition. This means that the functions registered with Spl_autoload_register () are preferred.

  According to the above, if Autoload_func is non-null, the __autoload () function cannot be executed automatically. If you want to use the Spl_autoload_register () function, you can still use the __autoload () function, you can add the __autoload function to the hash table by Spl_autoload_register (), that is, Spl_autoload_register (__autoload ()). The following code example shows how to register a static public method for a common method and class.

The method of registering a common function.

<? php/*** @ Normal function call method, you can call the suffix name of. PHP and. class.php class file */function loadfielendofphp ($classname) {$fileName = $classname. ". PHP ";" if (File_exist ($fileName)) {require_once ("$fileName");} else {echo $fileName. "Doesn ' t exist!"}} function loadfielendofclassphp ($classname) {$fileName = $classname. ". Class.php ", if (File_exist ($fileName)) {require_once (" $fileName ");} else {echo $fileName." Doesn ' t exist! "} Spl_autoload_register ("loadfielendofphp"); Spl_autoload_register ("loadfielendofclassphp");}

The registration method for static load functions in a class.

< the call method of a static member function in the @ class, which invokes a file with the suffix named. php and. php/*** */class Test {public static function loadfielendofphp ($classname) {$fileName = $classname. ". PHP "; if (File_exist ($fileName)) {require_once (" $fileName ");} else {echo $fileName. "Doesn ' t exist!"}} public static function loadfielendofclassphp ($classname) {$fileName = $classname. ". Class.php ", if (File_exist ($fileName)) {require_once (" $fileName ");} else {echo $fileName. "Doesn ' t exist!"}} Spl_autoload_register (Array ("Test", "loadfielendofphp"));         Spl_autoload_register ("test::loadfielendofphp"); Another way of writing on the previous line is not to use an array to complete the registration; Spl_autoload_register ("Test", "loadfielendofclassphp");//spl_autoload_register    ("test::loadfielendofclassphp"); Another way of writing the third line is not to complete the registration using an array;} 

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.