PHP Namespaces and automatic load class _php instances

Source: Internet
Author: User
Tags autoload class definition constant php language

The PHP namespace (namespace) is php5.3. This concept is already very early in C #, PHP in the namespace in fact and C # concept is the same.

Why do you use namespace in PHP?

Suppose that if you do not use namespace, the name of each class in a project must be fixed. Because when PHP is new, whether it calls AutoLoad or invokes a loaded class, there is a file for the class name. So in the absence of namespace, we will think of various naming conventions to distinguish between different classes, such as Project1_school1_class1_student or project2_school_class_student.

After the introduction of the namespace can be effectively circumvented, a namespace is equivalent to a file path, to find this class, it will go to the corresponding file path to find the class definition file.

Background

Recently a friend asked me what the PHP namespace is, but because the long-term does not do the development, the author has actually forgotten almost, so also can not answer. Just remember and Java is very similar. After a second check of the official PHP document, and compared to Java, Java namespace actually from the JVM itself, the JVM is based on class bytecode file loading classes, because the class is very easy to duplicate the case, in other words, class bytecode files will also appear duplicate, so You need to use a directory to manage different bytecode files, and in order to ensure normal loading, you need a namespace for this mechanism. Of course, it can be said that because of the existence of namespaces have the way of directory management. But PHP is not the same as Java, PHP is a dynamic scripting language, its code is scattered in all scripts, when the need to use the Include function to load the corresponding file, so the PHP namespace, is actually based on PHP automatic loading class, automatic load class implementation to ensure that PHP The meaning of the namespace existence.

Namespaces Overview

The namespace, as far as I know, should have originated in C + + language, after the c++98 standard, in order to ensure that a variety of naming does not coincide with a solution introduced. Today's object-oriented language basically has this mechanism, of course, in addition to namespaces, there are many ways, such as modularity, but in fact these mechanisms are used to solve the encapsulation problem, so I personally think there is no good or bad points. First the PHP official document code out to sneak

<?php
namespace My\name//reference "define namespace" subsection
class MyClass {}
function MyFunction () {}
const MYCONST = 1;
$a = new MyClass;
$c = new \my\name\myclass; Refer to the "Global Space" section
$a = strlen (' Hi ');//reference "use namespaces: Fallback global Functions/Constants" subsection
$d = namespace\myconst;//reference "namespace operator and __names PACE__ constant "subsection
$d = __namespace__. ' \myconst ';
ECHO constant ($d); Refer to the "Namespaces and Dynamic Language Features" section
?>

Very easy to understand code, from the above code can see the definition of the namespace of PHP, but the author personally think it is very anti-human, actually use the backslash to separate the namespace path. It is important to note, however, that namespaces called PHP or PHP, and namespaces that begin with these names (such as php\classes), are reserved for use as language kernels and should not be used in user-space code.

Defining namespaces

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

<?php
namespace MyProject;
Const CONNECT_OK = 1;
Class Connection {/* ... */}
function Connect () {/* ... */}
?>

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

<?php
Declare (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, and generally, a file contains a class, so also do not need curly braces to split the namespace scope.

Using namespaces

For a namespace path, there are three different forms

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 resolved 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 is resolved to Currentnamespace\subnamespace\foo. If the code that uses Foo is global and does not contain code in any namespace, Foo will be parsed as Subnamespace\foo.

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 resolved to the literal name (literal name) Currentnamespace\foo in the code.

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

 <?php namespace NamespaceName; class ClassName {function __construct () {echo __metho
d__, "\ n";
} function FuncName () {echo __function__, "\ n";} const CONSTNAME = "namespaced";
Include ' example1.php ';
$a = ' classname '; $obj = new $a;
Prints classname::__construct $b = ' funcname '; $b (); Prints funcname Echo constant (' constname '), "\ n"; Prints Global/* The IF using double quotes, "\\namespacename\\classname" must be used */$a = ' \namespacename\cl
Assname '; $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\funcname echo constant (' \namespacename\constname '), "\ n"; Prints namespaced Echo constant (' namespacename\constname '), "\ n"; Also prints namespaced 

One thing to note, however, is the distinction between single and double quotes, where single quotes can be handled without processing, and double quotes must use a translation symbol such as \.

The Java language uses the import mechanism to introduce namespaces, and because Java can specify the class name, Java is allowed to import up to a specific class, while PHP can specify classes, constants, methods, and so on in a namespace and support namespace aliases.

<?php
namespace Foo;
Use My\full\classname as Another;
The following example is the same use My\full\nsname as the 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 Foo\another Like
$obj = new Another;//Instantiate My\full\classname object
nsname\subns\func ();//Call function My\full\nsname\subns\func
$a = new Arrayobject (Array (1)); Instantiate the Arrayobject object
///If you do not use the \arrayobject, instantiate a Foo\arrayobject object
func ();//Calls function my\full\f Unctionname
echo CONSTANT;//echoes the value of My\full\constant
?>

Name resolution rules

First, the three types of names mentioned earlier, name resolution follows these rules:

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

All unqualified and qualified names (not fully qualified names) are converted at compile time according to the current import rule. 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 a namespace, all qualified names that are not converted according to the import rule precede them with the current namespace name. For example, C\d\e () is called inside the namespace a\b, then 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 (replace the short import name with the full name). For example, if the namespace a\b\c is imported as C, the new C () is converted to the new a\b\c ().

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

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

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

Calls to unqualified or qualified name classes (not fully qualified names) within a namespace (such as a\b) are resolved at run time. The following 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.

Try to load the class a\b\c automatically.

Resolution of New D\e ():

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

Try to load the class a\b\d\e automatically.

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

From the rules above, actually the import rules of PHP and Java are somewhat similar, but there are different, mainly because Java is completely object-oriented, and PHP is essentially an object-based language.

Auto Load Class

In early PHP development, the most annoying thing about developers is that a bunch of include functions contain a bunch of files, and the PHP object-oriented concept was really bad in the early days because PHP, as a scripting language, doesn't have a program entry, so the temptation to execute the script sequentially is really great, even if object-oriented development, But the lack of excellent module-Division import mechanism, the 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 connect, and then each page rendering is the same to go to the process. Of course, this is the history of WordPress baggage, and in support of the old version of PHP in the case of the WordPress code has been written enough to optimize.

There's no need for such trouble in the PHP5. Because a __autoload () function can be defined, the function is started when an undefined class is invoked, so that a final remedy is made before the error is thrown, but the function's intent has been completely misinterpreted and is now used for automatic loading.

Note that this function is not actually recommended, 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 automatic mount function that needs to be registered, and if this entry is empty, the Spl_autoload function is registered.

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

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

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

void Spl_autoload (String $class _name [, String $file _extensions])
Because the default implementation of this function is through the C language, so here is a PHP language implementation specification.

<?php
//Your custom class dir
define (' Class_dir ', ' class/')
//Add Your class dir to include path
set_ 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 filenames
Spl_autoload_extensi ONS ('. class.php ');
Use default AutoLoad implementation
Spl_autoload_register ();
? >

It's basically similar to this one. In fact, the combination of namespaces and automatic loading classes is basically through the form of a path

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

Replaces the namespace path with the actual path.

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

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.