PHP Namespaces and auto-load classes

Source: Internet
Author: User
Tags autoload php definition

Background

Recently a friend asked me how the PHP namespace is, but because of the long-term not to do development, I actually have forgotten almost, so also can not answer. Just remember that it looks like Java. After the subsequent re-check the official PHP document, and in contrast to Java, the Java namespace is actually derived from the JVM itself mechanism, the JVM is based on class bytecode file loading classes, because the class is prone to duplicate names, in other words, class bytecode files will also appear the same name, so You need to use a directory to manage different bytecode files, and to ensure that the load is normal, you need a mechanism for namespaces. Of course, it can be said that the existence of a namespace is the way directory management. But PHP is not the same as Java, PHP is a dynamic scripting language, its code is scattered in all scripts, when needed to use the Include function to load the corresponding file, so the PHP namespace, is actually based on the PHP automatic loading class, automatic loading class implementation to ensure that PHP life The significance of the existence of a name space.

Namespaces Overview

Namespaces as far as the author knows should originate from the C + + language, after the c++98 standard, in order to ensure that the various names do not coincide with a solution introduced. Now the object-oriented language basically has this mechanism, of course, in addition to namespaces, there are many ways, such as modular, but in fact, these mechanisms are used to solve the encapsulation problem, so I personally think there is no good or bad points. Just pull out the PHP official document code and sneak out.

 
  

Very easy to understand code, from the above code can see the PHP definition of the namespace, but I personally think its definition is very anti-human, actually use a backslash to separate the namespace path. One thing to note, though, is that namespaces named PHP or PHP, and namespaces that start with those names (such as php\classes), are reserved for use as a language kernel and should not be used in user-space code.

Define namespaces

The PHP namespace feature can only be used in versions above PHP5.3.0, and for a namespace, only classes, interfaces, functions, and constants are included in the namespace.

 
  

Of course, you can also use curly braces to contain all the content you need, like this.

 
  

However, this can easily cause indentation problems, so I do not recommend the use of, and generally, a file contains a class, so do not need curly braces to split the namespace scope.

Using namespaces

There are three types of namespaces for a namespace path

    1. Unqualified name, or class name that does not contain a prefix. For example $a =new foo (), or Foo::staticmethod ();. If the current namespace is Currentnamespace, Foo will be parsed to Currentnamespace\foo. If the code that uses Foo is global and does not contain code in any namespace, Foo will be parsed as Foo '.

    2. A qualified name, or a name that contains a prefix, such as $a = new Subnamespace\foo (), or Subnamespace\foo::staticmethod ();. If the current namespace is Currentnamespace, Foo will be parsed to Currentnamespace\subnamespace\foo. If the code that uses Foo is global and does not contain code in any namespace, Foo is parsed as Subnamespace\foo.

    3. The fully qualified name, or contains the name of the global prefix operator, for example, $a = new \currentnamespace\foo (), or \currentnamespace\foo::staticmethod ();. In this case, Foo is always parsed into the literal name (literal name) Currentnamespace\foo in the code.

Because of the nature of the dynamic language of PHP itself, it is possible to dynamically access elements within a namespace using strings.

 
  

One thing to note, however, is the distinction between single and double quotes, where single quotes do not need to process \ 's translation, and double quotes must use a translation notation such as \ \.

The Java language uses the import mechanism to introduce namespaces, and because Java can be assigned to a class name, Java is imported to only a specific class, and PHP can be assigned to classes, constants, methods, and so on in a namespace, and namespace aliases are supported.

 
  

Name resolution rules

The first is the three types of names mentioned earlier, and name resolution follows these rules:

  1. Calls to fully qualified names for functions, classes, and constants are parsed at compile time. For example, new \a\b resolves to class a\b.

  2. All unqualified and qualified names (not fully qualified names) are converted at compile time according to the current import rules. For example, if the namespace a\b\c is imported as C, then the call to C\d\e () is converted to a\b\c\d\e ().

  3. Inside the namespace, all qualified names that are not translated according to the import rule are preceded by the current namespace name. For example, if you call C\d\e () inside the namespace a\b, C\d\e () is converted to a\b\c\d\e ().

  4. Unqualified class names are converted at compile time based on the current import rule (instead of the short import name with the full name). For example, if the namespace a\b\c is imported as C, then new C () is converted to new a\b\c ().

  5. Within a namespace (for example, a\b), a function call to an unqualified name is parsed at run time. For example, the call to function foo () is parsed like this:

    • Look for a function named A\b\foo () in the current namespace

    • Try to find and invoke the function foo () in global space.

  6. Calls to unqualified or qualified name classes (not fully qualified names) within a namespace (for example, a\b) are resolved at run time. Here is the parsing process for calling new C () and New D\e ():

    • Resolution of New C ():

      • Finds the A\b\c class in the current namespace.

      • Attempt to automatically load class a\b\c.

    • Parsing of New D\e ():

      • Precede the class name with the current namespace name into: A\b\d\e, and then look for the class.

      • Attempt to automatically load class a\b\d\e.

    • In order to refer to global classes in the global namespace, you must use the fully qualified name new \c ().

From the above rules, in fact, PHP import rules and Java a bit similar, but there are different, mainly because Java is completely object-oriented, and PHP is essentially an object-based language.

Auto Load Class

In the early development of PHP, the most annoying thing for developers is that a bunch of include functions contain a lot of files, and early on PHP's object-oriented concept is really poor, because PHP as a scripting language, there is no program entrance, so script execution of the temptation is very large, even if object-oriented development, But the lack of a very good module partition import mechanism, code can be said to be difficult to have beauty, the largest representative is Wordpress. If a friend has seen this typical project, it can be very painful, because the various initialization, business processes are scattered in various files, using the Include function to join, and then each page rendering is the same to go through the process. Of course, this is the historical burden of WordPress, and in support of the old version of PHP, the WordPress code has been written enough to optimize.

This is not necessary in PHP5, because a __autoload () function can be defined, and when an undefined class is invoked, the function is launched to make a final remedy before the error is thrown, but the intent of the function has been completely misinterpreted and is now used for automatic loading.

Note that this function is not actually recommended, but instead, you should now use Spl_autoload_register () to register the class's auto-load function.

BOOL Spl_autoload_register ([Callable $autoload _function [, bool $throw = True [, bool $prepend = false]]])

Autoload_function is an auto-load function that requires registration, and if this entry is empty, the Spl_autoload function is registered,

Throw this parameter sets whether Spl_autoload_register () throws an exception when Autoload_function fails to register successfully.

Prepend if True, Spl_autoload_register () adds the function to the top of the queue, not the tail of the queue.

The Spl_autoload function is mentioned above, in fact the specification of the registered function should follow this function, the function declaration is as follows:

void Spl_autoload (String $class _name [, String $file _extensions])

Since the default implementation of this function is in C, the implementation specification for a PHP language is given here.

 
  

It's roughly the same as this one. In fact, the combination of namespaces and auto-load classes is basically through the path form

function __autoload () {    $dir = './libralies ';    Set_include_path (Get_include_path (). Path_separator. $DIR);    $class = str_replace (' \ \ ', '/', $class). '. php ';     Require_once ($class);}

Replace the namespace path with the actual path.

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