PHP automatically loads autoload and namespace application summary, autoload namespace

Source: Internet
Author: User
Tags autoload php framework

PHP automatically loads autoload and namespace application summary, autoload namespace

Let's talk about what a namespace is.

"What is a namespace? In a broad sense, namespace is a way to encapsulate things. This abstract concept can be seen in many places. For example, a directory in the operating system is used to group related files. For files in the directory, it plays the role of namespace. For example, the file foo.txt can exist in the/home/greg and/home/other directories at the same time, but there cannot be two foo.txt files in the same directory. In addition, when accessing the foo.txt file outside the/home/greg directory, we must put the directory name and directory separator before the file name to get/home/greg/foo.txt. This principle is applied to the field of programming as a namespace concept ."

PHP's automatic loading means that when we load the instantiated class, we do not need to manually write require to import this class. PHP file. The program will automatically help us load and import it. With the namespace specification, we can easily handle the loading and calling of different classes in complex systems.

1. Principles of automatic loading and the use of _ autoload

The principle of automatic loading is that when we instantiate a class, if PHP cannot find this class, it will automatically call the _ autoload ($ class_name) method in this file, the new class_name becomes the parameter of this method. Therefore, in this method, we can determine and divide the new class_name according to our needs, and then go to the corresponding path class file of require to implement automatic loading.

Let's take a look at the automatic call of _ autoload (), for example:

Index. php

<?php $db = new Db();

If we do not manually import the Db class, the program may report an error saying that this class cannot be found:

Fatal error: Uncaught Error: Class 'db' not found in D: \ web \ helloweba \ demo \ 2017 \ autoload \ index. php: 2 Stack trace: #0 {main} thrown in D: \ web \ helloweba \ demo \ 2017 \ autoload \ index. php on line 2

Now let's add the _ autoload () method and then look at it:

$db = new DB();function __autoload($className) { echo $className; exit();}

According to the description of the automatic loading mechanism above, the Db will be output, that is, the Class Name of the new class we need. Therefore, we can load the class library file in the _ autoload () method as needed.

2. spl_autoload_register automatic loading

If it is a small project, use _ autoload () to implement basic automatic loading. However, if a project is large, or you need different automatic loading methods to load files in different paths, _ autoload will be available at this time, because only one _ autoload () function is allowed in a project, because PHP does not allow repeated function names, that is, you cannot declare two _ autoload () function files, otherwise, a fatal error is reported. What should we do? Rest assured, you have come up with PHP. So another awesome function like spl_autoload_register () was born and replaced with it. It is more efficient and flexible.

First, let's take a look at how it works. Add the following code to index. php.

<?php spl_autoload_register(function($className){ if (is_file('./Lib/' . $className . '.php')) { require './Lib/' . $className . '.php'; }});$db = new Db();$db::test();

Add the following code to the Lib \ Db. php file:

<?php class Db{ public static function test() { echo 'Test'; }}

Run index. after php, when new Db () is called, spl_autoload_register will automatically go to The lib/directory to find the corresponding Db. PHP file. After successful execution, you can run $ db: test ();. Similarly, if multiple php class files exist in the Lib \ directory, they can be directly called in index. php without using multiple require files.

That is to say, spl_autoload_register can be used multiple times. This solves the short board of _ autoload. If a page has multiple spl_autoload_register, the execution order is in the registration order, find them one by one. If they are found, stop them.

3. spl_autoload_register automatic loading and namespace

For a very complex system, the directory structure is also very complex. The standardized namespace solves the problem of a large number of files, functions, and classes with duplicate names in complex paths. Automatic loading is now the cornerstone of the modern PHP framework. It is basically implemented by spl_autoload_register. Therefore, spl_autoload_register + namespace has become the mainstream.

The namespace naming rules are already very standardized according to the series of dsrs. Therefore, you can find detailed Paths Based on the namespace to find class files.

We use the simplest example to illustrate how a complex system automatically loads class files.

First, we prepare the system directory structure:

----/Lib // class directory -- Db. php -- Say. php ---- autoload. php // automatically load the function ---- index. php // Homepage

The above is a basic system directory. What we need to achieve is to use namespace and automatic loading to directly call multiple classes under the Lib directory on the homepage index. php.

We prepare two column files:

Db. php

<?php namespace Lib;class Db{ public function __construct() { //echo 'Hello Db'; } public static function test() { echo 'Test'; }}Say.php<?phpnamespace Lib;class Say { public function __construct() { //echo 'Hello'; } public function hello() { echo 'say hello'; }}

The namespace Lib is added to the above two common class files, indicating that the class files belong to the Lib \ directory name, of course, you can use a different name to indicate your project name.

Now let's look at autoload. php:

<? Php spl_autoload_register (function ($ class) {$ prefix = 'lib \ '; $ base_dir = _ DIR __. '/Lib/'; // the class use the namespace prefix? $ Len = strlen ($ prefix); if (strncmp ($ prefix, $ class, $ len )! = 0) {// no, move to the next registered autoloader return;} $ relative_class = substr ($ class, $ len); // compatible with Linux Files. In Windows (// and \), $ file = $ base_dir. str_replace ('\', '/', $ relative_class ). '. php '; if (file_exists ($ file) {require $ file ;}});

The above Code uses the spl_autoload_register () function to first determine whether a namespace is used, and then verify whether the class file to be called exists. If so, the require class file is used.

Now we can call index. php on the homepage as follows:

<?php use Lib\Db;use Lib\Say;require './autoload.php';$db = new Db();$db::test();$say = new Say;$say->hello();

We only need to use a require to load the autoload. php loads in and uses the use keyword to change the class file path to an absolute path. Of course, you can also write the path when calling the class, such as new Lib \ Db ();, however, when multiple classes are involved to call each other, it will be tricky. Therefore, we should use to process the path at the beginning of the file.

Next, you can directly call all types of files under the Lib/directory. You can put multiple class files under the Lib/directory to try.

Run index. php to see if it is as expected.

Conclusion

This article briefly introduces automatic loading and namespace usage. In actual development, we seldom pay attention to the issue of autoload automatic loading, because most modern PHP frameworks have already handled the issue of automatic file loading. Developers only need to focus on business code and use standard namespaces. Of course, if you want to develop a project by yourself without relying on a large framework or developing a php framework by yourself, you should be familiar with autoload to automatically load this good thing, after all, it can make us "lazy" and save a lot of trouble.

In modern php, components installed in Composer mode can be automatically loaded through autoload, so it is still a "lazy" word that brings us excellent development efficiency.

Summary

The above is a summary of PHP automatic loading of autoload and namespace. I hope it will help you. If you have any questions, please leave a message, the editor will reply to you in a timely manner. Thank you very much for your support for the help House website!

Related Article

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.