PHP namespace and automatic loading class, PHP namespace loading class

Source: Internet
Author: User
Tags autoload

PHP namespace and automatic loading class, PHP namespace loading class

PHP namespace is available only after php5.3. This concept has been available in C # for a long time. The namespace in php is actually the same as that in c.

Why use namespace in php?

If namespace is not used, the name of each class in a project must be fixed. Because when php is new, whether it is calling autoload or calling loaded classes, there is a file corresponding to the class name. When there is no namespace, we will consider various naming rules to distinguish different classes, such as project1_school1_class1_Student or project2_school_class_Student.

After namespace is introduced, this can be effectively avoided. a namespace is equivalent to a corresponding file path. When searching for this class, the corresponding file path will be used to find the class definition file.

Background

Recently, a friend asked me what the PHP namespace is like. But since I haven't developed it for a long time, I have forgotten it, so I cannot answer it. I just remember it looks exactly like Java. Afterwards, I re-checked the official PHP documentation and compared it with Java. the Java namespace actually comes from the JVM mechanism. The JVM is based on the class bytecode file loading class, because classes are prone to duplicate names, in other words, class bytecode files may also have duplicate names, you need to use directories to manage different bytecode files. To ensure normal loading, therefore, the namespace mechanism is required. Of course, it can also be said that the existence of the namespace provides the Directory management method. However, PHP and Java are different. PHP is a dynamic scripting language, and its code is scattered in all scripts. When necessary, the include function is used to load the corresponding files, therefore, the PHP namespace is actually based on PHP's automatic loading class. The automatic loading class can ensure the meaning of the PHP namespace.

Namespace Overview

As far as I know, the namespace should first come from the C ++ language. After the C ++ 98 standard, it is a solution to ensure the non-overlapping naming. Currently, this mechanism is basically available for object-oriented languages. Of course, apart from namespaces, there are many other methods, such as modularization. However, these mechanisms are actually used to solve encapsulation problems, therefore, I personally think there is no good or bad. First, pull out the official PHP document code.

<? Phpnamespace my \ name; // refer to "definition namespace" section class MyClass {} function myfunction () {} const MYCONST = 1; $ a = new MyClass; $ c = new \ my \ name \ MyClass; // refer to "global space" section $ a = strlen ('Hi'); // refer to "use namespace: reserve global functions/constants "section $ d = namespace \ MYCONST; // refer to" namespace operator and _ NAMESPACE _ constant "section $ d = _ NAMESPACE __. '\ myconst'; echo constant ($ d); // refer to the "namespaces and Dynamic Language Features" section?>

The code is very easy to understand. From the code above, we can see what the PHP-defined namespace is like. However, I personally think the definition is very anti-human, and actually use a backslash to separate the namespace paths. Note that the namespace named PHP or php and the namespace starting with these names (such as PHP \ Classes) are reserved for use as the language kernel, it should not be used in user space code.

Define a namespace

The PHP namespace function can only be used in PHP5.3.0 or later versions. 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 brackets to include all the required content, just 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 it, and in general, a file contains a class, so no curly brackets are required to split the namespace range.

Use namespace

There are three types of namespaces

A non-qualified name, or a 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 as currentnamespace \ foo. If the code using foo is global and is not included in any namespace, foo will be parsed as foo '.

A qualified name, or a name containing a prefix, such as $ a = new subnamespace \ foo (); or subnamespace \ foo: staticmethod ();. If the current namespace is currentnamespace, foo will be parsed as currentnamespace \ subnamespace \ foo. If the code using foo is global and is not included in any namespace, foo will be parsed as subnamespace \ foo.

A fully qualified name or a name that contains the global prefix operator, for example, $ a = new \ currentnamespace \ foo (); or \ currentnamespace \ foo: staticmethod ();. In this case, foo is always parsed as the text name (literal name) currentnamespace \ foo in the code.

Due to the Dynamic Language Features of PHP, you can use strings to dynamically access elements in the namespace.

<?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 double quotes, "\\namespacename\\classname" must be used */$a = '\namespacename\classname';$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?>

However, one thing to note is the difference between Single and Double quotation marks. single quotation marks do not need to be processed \'s translation, but double quotation marks must use \ and other translation symbols.

The Java language uses the import mechanism to introduce namespaces. Because Java can be specified to the class name, Java can only be imported to a specific class at most, PHP can specify classes, constants, and methods in a namespace, and supports namespaces.

<? Phpnamespace foo; use My \ Full \ Classname as Another; // The following example is the same as use My \ Full \ NSname as NSname; // import a global class use ArrayObject; // importing a function (PHP 5.6 +) use function My \ Full \ functionName; // aliasing a function (PHP 5.6 +) use function My \ Full \ functionName as func; // importing a constant (PHP 5.6 +) use const My \ Full \ CONSTANT $ obj = new namespace \ Another; // instantiate the foo \ Another object $ obj = new Another; // instantiate the My \ Full \ Classname object NSname \ subns \ func (); // call the function My \ Full \ NSname \ subns \ func $ a = new ArrayObject (array (1 )); // instantiate an ArrayObject object // If "use \ ArrayObject" is not used, instantiate a foo \ ArrayObject object func (); // callfunction My \ Full \ functionNameecho CONSTANT; // echoes the value of My \ Full \ CONSTANT?>

Name resolution rules

The first is the three name types mentioned above. name resolution follows the following rules:

Calls to fully qualified functions, classes, and constants are parsed during compilation. For example, new \ A \ B is parsed as class A \ B.

All unqualified names and qualified names (not fully qualified names) are converted during compilation according to the current import rules. For example, if the namespace A \ B \ C is imported as C () is converted to A \ B \ C \ D \ e ().

Within the namespace, all qualified names that are not converted according to the import rules will be prefixed with the current namespace name. For example, if C \ D \ e () is called in namespace A \ B, C \ D \ e () is converted to A \ B \ C \ D \ e ().

The unqualified class name is converted during compilation according to the current import rule (the short Import Name is replaced by the full name ). For example, if the namespace A \ B \ C is imported as C, new C () is converted to new A \ B \ C ().

In A namespace (for example, A \ B), function calls with non-qualified names are parsed at runtime. For example, the call to function foo () is parsed as follows:

Find the function named A \ B \ foo () in the current namespace

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

Calls to A non-qualified name or qualified name class (not fully qualified name) within A namespace (for example, A \ B) are resolved at runtime. The following is the parsing process of calling new C () and new D \ E:

New C () parsing:

Find the \ B \ C Class in the current namespace.

Try to automatically load Class A \ B \ C.

New D \ E () parsing:

Add the name of The namespace before the class name to A \ B \ D \ E, and then search for the class.

Try to automatically load Class A \ B \ D \ E.

To reference global classes in a global namespace, you must use the fully qualified name new \ C ().

From the above rules, the import rules of PHP are a bit similar to those of Java, but they are different, mainly because Java is completely object-oriented, PHP is essentially an object-based language.

Automatic loading class

In early PHP development, the most annoying thing for developers was that a bunch of include functions contained a lot of files, and the PHP object-oriented concept was indeed too bad in the early days, as PHP is a scripting language, there is no program entry, so the temptation to execute scripts in sequence is really great. Even if it is object-oriented development, it lacks an excellent module division import mechanism, code can be said to be difficult to be aesthetic, the biggest representative is Wordpress. If you have read this typical project, you may feel very painful, because various initialization and business processes are scattered in different files, and the include function is used for cohesion, then every page rendering process is the same. Of course, this is the historical burden of Wordpress, And the Wordpress code has been well optimized when the old version of PHP is supported.

PHP5 does not need to be so troublesome, because a _ autoload () function can be defined. When an undefined class is called, this function will be started, so as to make the final remedy before throwing an error, but the intention of this function has been completely misinterpreted and used for automatic loading.

Note that this function is not recommended. Instead, you should use spl_autoload_register () to register the automatic loading function of the class.

Bool spl_autoload_register ([callable $ autoload_function [, bool $ throw = true [, bool $ prepend = false])
Autoload_function is an automatic loading function to be registered. If this item is null, The spl_autoload function is registered,

Throw this parameter sets whether spl_autoload_register () throws an exception when autoload_function cannot be successfully registered.

If prepend is true, spl_autoload_register () will add the function to the first of the queue, rather than the end of the queue.

The spl_autoload function is mentioned above. In fact, the registration function specification should follow this function. The function declaration is as follows:

Void spl_autoload (string $ class_name [, string $ file_extensions])
Because this function is implemented in C by default, a PHP implementation specification is provided here.

<?php// Your custom class dirdefine('CLASS_DIR', 'class/')// Add your class dir to include pathset_include_path(get_include_path().PATH_SEPARATOR.CLASS_DIR);// You can use this trick to make autoloader look for commonly used "My.class.php" type filenamesspl_autoload_extensions('.class.php');// Use default autoload implementationspl_autoload_register();?>

In general, it is similar to this. In fact, the combination of namespaces and automatically loaded classes is basically in the form of paths.

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 the PHP namespace and automatic loading class introduced by xiaobian. I hope it will help you!

Articles you may be interested in:
  • PHP namespace dynamic access and usage skills
  • Usage basics and examples of PHP namespaces
  • PHP Object-Oriented Programming (oop) learning notes (5)-PHP namespace
  • Simple PHP Namespace tutorial
  • Php namespace learning details
  • PHP Namespace usage
  • Php simplexmlElement: namespace implementation code for operating xml
  • New namespace rule parsing and advanced functions in PHP 5.3
  • Auto load of the dependency management tool Composer in PHP)
  • About the PHP autoLoad automatic loading mechanism
  • PHP spl_autoload_register for automatic loading
  • Use of PHP autoload automatic loading mechanism
  • Two Methods for php automatic loading
  • Php object-oriented full strategy (17th) 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.