PHP Automatic loading function, automatic loading method, automatic loading class

Source: Internet
Author: User
Tags autoload spl php class php framework

In the process of PHP development, if you want to introduce a class from the outside, you will typically use the include and require methods to include the file that defines the class. This is not a big problem when it comes to small-scale development. However, in large-scale development projects, doing so generates a large number of require or include method calls, which makes the code difficult to maintain without compromising efficiency, and the cost of require_once is great.

Before PHP5, each PHP framework, if it was to implement the automatic loading of classes, would typically implement a class or function that iterates through the directory and automatically loads all files that conform to the Convention rules by some Convention. Of course, PHP5 's previous support for object-oriented is not very good, and the use of classes is not very frequent now. After PHP5, the Zend engine calls the __autoload function automatically when the PHP class is loaded, if the file is not included in the class, or if the class name is wrong. This function requires the user to implement the __autoload function themselves. After the PHP5.1.2 version, you can use the Spl_autoload_register function to customize the auto-load handler function. When this function is not called, the SPL custom spl_autoload function is used by default.

The default implementation of the Spl_autoload function if you call the Autoload_register () function without any arguments, this function is automatically used later when you make a __autoload () call.

SPL has two different function spl_autoload, Spl_autoload_call, to implement different automatic loading mechanisms by pointing autoload_func to these two different function addresses.

Spl_autoload is the default auto-load function implemented by SPL, and its functionality is relatively simple. It can receive two parameters, the first parameter is $class_name, the class name, the second parameter $file_extensions is optional, represents the class file extension "title=" extension "> extension, you can $file_ Specify multiple extension "title=" extension "> Extension" in extensions, separated by semicolons, if not specified, it will use the default extension "title=" extension "> 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 paths (if you don't specify $file_extensions parameters ), if found, loads the class file. You can manually use Spl_autoload ("person", ". class.php") to load the person class. In fact, it's about the same as require/include. It can specify multiple extension "title=" extension "> extension.

How to let spl_autoload automatically function, that is, Autoload_func point to Spl_autoload? The answer is to use the Spl_autoload_register function. When you call Spl_autoload_register () for the first time in a PHP script, you can point autoload_func to spl_autoload without using any parameters.

With the instructions above, we know that the function of spl_autoload is relatively simple, and it is implemented in the SPL extension, and we cannot extend its functionality. What if you want to implement your own more flexible auto-loading mechanism? At this point, the Spl_autoload_call function shines.

Let's take a look at what's amazing about Spl_autoload_call's implementation. Inside the SPL module, there is a global variable autoload_functions, which is essentially a hashtable, but we can simply consider it as a linked list, and each element in the list is a function pointer to a function that has the automatic load class function. The implementation of the Spl_autoload_call itself is simple, simply sequential execution of each function in the list, after each function is completed to determine whether the required class has been loaded, if the load successfully returned directly, no longer continue to execute the list of other functions. If all functions in this list are executed after the class has not been loaded, spl_autoload_call exits without reporting an error to the user. Therefore, using the AutoLoad mechanism does not guarantee that the class will be able to automatically load correctly, the key is to see how your auto-loading function is implemented.

The standard library approach in PHP5 Spl_autoload equivalent to implementing its own __autoload

<?php    function __autoload ($classname) {        if (is_file ($classname. '). php ') {            include $classname. php ';        } ElseIf (Is_file ($classname. Inc ') {            include $classname. Inc ';        }    }

It will automatically look for a. php/.inc file with the same name as $classname in the registration directory. Of course, you can also specify a specific type of file by registering the extension

<?php    spl_autoload_extensions ('. Php,.inc,.some ');

In this way, it also searches for. some files. By default, PHP will not start spl_autoload, then how to automatically let spl_autoload take effect? Method is

<?php    Spl_autoload_register ();

Spl_autoload_register has a $callback parameter, if not specified, it will automatically register spl_autoload, in order to be able to search for more automatic loading directory, you can set the automatic loading directory before the code

<?php    Set_include_path (Get_include_path (). Path_separator. ' Some/path '. Directory_separator);

This way, when PHP cannot find the specified class, it is looked up in the directory specified by Set_include_path.

These methods are commonly used in PHP frameworks. For example, to link up the above introduction:

<?phpset_include_path (Get_include_path (). Path_separator. ' Some/path '. Directory_separator); Spl_autoload_extensions ('. Php,.inc,.some '); Spl_autoload_register ();

When you want to load the ClassA class under Some/path, it looks for classa.php or Classa.inc or classa.some in the directory, so you can safely use new ClassA or extends ClassA

<?php    ClassB extends ClassA {        //code:    }       $a = new ClassA;    

Spl_autoload

Spl_autoload_register registering an auto-load function function parameter a function that is loaded automatically when the class does not exist

Spl_autoload_call attempt to call all registered auto-load functions to load the request class

Spl_autoload_extensions registers and returns the default file name extension used by the Spl_autoload function. When this function is called without any arguments, it returns a list of the current file name extensions, separated by commas. To modify the list of file extensions, call this function with a new comma-delimited list of extension names. Chinese Note: The default Spl_autoload function uses the extension ". inc,.php". Example: Spl_autoload_extensions (". Inc,. PHP,. lib,. lib.php");

Spl_autoload_unregister function name when registering a registered auto-load function parameter

Spl_autoload_functions returns all registered Z auto-load function functions.

1. __autoload Example:

    function __autoload ($class _name) {         echo ' __autload class: ', $class _name, ' <br/> ';      }            New Demo ();  

The above code will be output at the end: __autload Class:demo.
And after this error shows: Fatal error:class ' Demo ' not found

We generally use the _autoload auto-load class as follows:

    <?php             function __autoload ($class _name) {     require_once ($class _name.  "class.php");       }          $memo = new Demo ();    

We can see that _autoload do at least three things, the first thing is to determine the class file name based on the class name, and the second thing is to determine the disk path where the class files are located (in our case the simplest case, the class is in the same folder as the PHP program file that called them), The third thing is to load the class from the disk file into the system. The third step is the simplest, only need to use Include/require. To implement the first step, the second step of the function, you must contract the class name and disk file mapping method at development time, so that we can find its corresponding disk file according to the class name.

Therefore, when there are a large number of class files to include, we just need to determine the corresponding rules, and then in the __autoload () function, the class name and the actual disk file corresponding to the effect of lazy loading can be achieved. From here we can also see that the most important implementation of the __autoload () function is the implementation of the class name and the actual disk file mapping rules.

But now the problem is, if in a system implementation, if you need to use a lot of other class libraries, these libraries may be developed by different development engineers, the class name and the actual disk file mapping rules are different. If you want to implement the automatic loading of the class library file, you must implement all the mapping rules in the __autoload () function, so the __autoload () function can be very complex or even impossible to implement. In the end, the __autoload () function can be bloated, and even if it can be achieved, it will have a significant negative impact on future maintenance and system efficiency. In this case, a new solution, the Spl_autoload_register () function.

2,

function __autoload ($class _name) {      echo ' __autload class: ', $class _name, ' <br/> ';  }  function ClassLoader ($class _name) {      echo ' SPL load class: ', $class _name, ' <br/> ';  }  Spl_autoload_register (' ClassLoader ');  

grammar spl_autoload_register  ([callback $autoload _function])     accepts two parameters: one is the function added to the auto-load stack, and the other is the flag that the loader cannot find when the class throws an exception. The first parameter is optional and, by default, points to the spl_autoload () function, which automatically finds the path with a lowercase class name and a. php extension or an. ini extension, or any registered to Spl_autoload_extensions () The file for other extensions in the function.

    <?php        class Calssloader         {public             static function loader ($classname)             {                 $class _file = Strtolower ($classname). ". PHP ";                 if (file_exists ($class _file)) {                     require_once ($class _file);}}         }          The method is static method         Spl_autoload_register (' Calssloader::loader ');          $test = new test ();  

once the Spl_autoload_register () function is called, all functions registered to the Spl_autoload_register () function are called sequentially, rather than automatically called, when the class is called undefined The AutoLoad () function. If this is to be avoided, a more secure initialization invocation method for the Spl_autoload_register () function is required:

    if (false = = = Spl_autoload_functions ()) {              if (function_exists (' __autoload ')) {                  spl_autoload_registe (' __ AutoLoad ', false);              }           }     

The Spl_autoload_functions () function returns an array of registered functions and returns a Boolean value of False if the SPL auto-load stack has not been initialized. Then, check to see if there is a function named __autoload () that, if present, can register it as the first function in the auto-load stack, preserving its functionality. After that, you can continue to register the auto-load function.

You can also call the Spl_autoload_register () function to register a callback function instead of providing a string name for the function. If you provide an array such as array (' class ', ' method '), it makes it possible to use an object's method.

Next, by calling the Spl_autoload_call (' className ') function, you can call the loader manually instead of trying to use that class. This function can be combined with the function class_exists (' ClassName ', false) to try to load a class and fail if none of the autoloader can find that class.

F (Spl_autoload_call (' className ') && class_exists (' ClassName ', false)) {              } else {          }  

The SPL auto-load function is provided by Spl_autoload (), Spl_autoload_register (), Spl_autoload_functions (), Spl_autoload_extensions () and Spl_ Provided by the Autoload_call () function.

PHP Automatic loading function, automatic loading method, automatic loading class

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.