PHP Namespaces and auto-load classes

Source: Internet
Author: User
Tags autoload php definition
PHP's namespace (namespace) is only available after php5.3. This article mainly introduces the PHP namespace and the automatic loading class related materials, the need for friends can refer to the following

PHP's namespace (namespace) is only available after php5.3. This concept is already very early in C #, and the namespace in PHP is actually the same as the C # concept.

Why should I use namespace in PHP?

Assuming that you do not use namespace, the name of each class in a project must be fixed. Because PHP has a file that corresponds to a class name, whether it's calling AutoLoad or calling a loaded class at new. So when there is no namespace, we think of various naming conventions to distinguish different classes, such as Project1_school1_class1_student or project2_school_class_student.

The introduction of namespace can be effectively circumvented, a namespace equivalent to a file path, when looking for this class, it will go to the corresponding file path to find the class definition file.

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 The meaning of the namespace existence.

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.

<?phpnamespace My\name; Refer to the "Defining Namespaces" subsection class MyClass {}function MyFunction () {}const myconst = 1; $a = new MyClass; $c = new \my\name\myclass; Refer to the "Global Space" subsection $ A = strlen (' Hi '); Refer to "Using namespaces: Fallback global Functions/Constants" subsection $d = namespace\myconst; Refer to "NAMESPACE operator and __namespace__ constant" subsection $d = __namespace__. ' \myconst '; echo constant ($d); Refer to the "Namespaces and Dynamic Language Features" subsection?>

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.

<?phpnamespace myproject;const CONNECT_OK = 1;class Connection {/* ... */}function CONNECT () {/* ... */}?>

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

<?phpdeclare (encoding= ' UTF-8 '); namespace MyProject {Const CONNECT_OK = 1;class Connection {/* ... */}function CONNECT () {/* ... */}}namespace {//Global code session_start (); $a = Myproject\connect (); Echo Myproject\connection::start ();}? >

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

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

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.

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.

<?phpnamespace namespacename;class classname{function __construct () {echo __method__, ' \ n ';}} function funcname () {echo __function__, ' \ n ';} Const CONSTNAME = "namespaced"; include ' example1.php '; $a = ' classname '; $obj = new $a; Prints classname::__construct$b = ' funcname '; $b (); Prints Funcnameecho constant (' constname '), "\ n"; Prints global/* Note that if using a double quotes, "\\namespacename\\classname" must be used */$a = ' \namespacename\clas Sname '; $obj = new $a; Prints namespacename\classname::__construct$a = ' namespacename\classname '; $obj = new $a; Also prints namespacename\classname::__construct$b = ' namespacename\funcname '; $b (); Prints namespacename\funcname$b = ' \namespacename\funcname '; $b (); Also prints Namespacename\funcnameecho constant (' \namespacename\constname '), "\ n"; Prints Namespacedecho constant (' namespacename\constname '), "\ n"; Also prints namespaced?>

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.

<?phpnamespace Foo;use My\full\classname as another;//The following example with use My\full\nsname as Nsname same use my\full\nsname;//import a Global class use arrayobject;//importing a function (PHP 5.6+) use function my\full\functionname;//aliasing a function (PHP 5.6+) US e function My\full\functionname as func;//importing a constant (PHP 5.6+) Use const MY\FULL\CONSTANT$OBJ = new Namespace\a nother; Instantiate Foo\another Object $obj = new Another; Instantiate the My\full\classname object Nsname\subns\func (); Call function my\full\nsname\subns\func$a = new Arrayobject (Array (1)); Instantiate Arrayobject object//If use \arrayobject is not used, instantiate a Foo\arrayobject object func (); Calls function My\full\functionnameecho CONSTANT; Echoes the value of my\full\constant?>

Name resolution rules

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

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.

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 ().

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 ().

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 ().

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.

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.

<?php//Your Custom Class Dirdefine (' Class_dir ', ' class/')//ADD Your class DIR to include Pathset_include_path (get_inc Lude_path (). Path_separator. CLASS_DIR);//You can use the this trick to make autoloader look for commonly used "My.class.php" type Filenamesspl_autoload_e Xtensions ('. class.php ');//Use default AutoLoad implementationspl_autoload_register (); >

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.

The above content is small to introduce you to the PHP namespace and automatic loading class, we hope to help!

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