Introduction to PHP namespaces and automatic loading mechanism ____php

Source: Internet
Author: User
Tags autoload php error

Include and require are two basic ways to introduce files in PHP. There's nothing wrong with using include and require directly in small scale development, but it can cause a lot of include and require accumulation in large projects. Such code is not elegant, execution efficiency is very low, and maintenance is also very difficult.

To solve this problem, part of the framework gives an introduction to the file's configuration list and introduces the required files when the object is initialized. But it just makes the code a little more concise, and the effect is still passable. After PHP5, with the completion of PHP object-oriented support, the __autoload function really makes automatic loading possible.

* The include and require features are the same, and they differ in that the include error only produces a warning, and require throws an error-terminating script.

* The only difference between include_once and include is that include_once checks whether the file has been introduced and, if so, does not repeat the introduction.

================= Automatic loading ==================

The easiest way to achieve automatic loading is to use the __autoload magic method. When a class that needs to be used is not introduced, the function is triggered before the PHP error, and the undefined class name is passed in as a parameter. As for the specific logic of the function, this needs to be implemented by the user himself.

First create a autoload.php to do a simple test:

When a class is undefined, the system automatically invokes
function __autoload ($class)
{/
    * specific processing logic */
    echo $class; simple output undefined class name
}

New HelloWorld ();

/**
 * Output HelloWorld and error information
 * Fatal error:class ' HelloWorld ' not found * *
 

This simple example shows that in the instantiation process of a class, the work done by the system is roughly the same:

/* Simulation System instantiation process/
function instance ($class)
{
    //If the class exists then return the example if
    (Class_exists ($class, False)) {
        return new $class ();
    }
    See if the AutoLoad function is user-defined
    if (function_exists (' __autoload ')) {
        __autoload ($class);//Last Chance introduced
    /
    / Check to see if the class exists
    if (Class_exists ($class, False)) {return
        new $class ();
    } else {//system: I can't do it
        throw new exc Eption (' Class not Found ');
    }

Having understood how the __autoload function works, let's use it to automate loading.

First create a class file (the recommended file name is the same as the class name), and the code is as follows:

class [ClassName] 
{
    //object is instantiated with the current name
    function __construct ()
    {
        echo ' 

(I've created a HelloWorld class to use as a demo) next we're going to define __autoload's specific logic so that it can be loaded automatically:

function __autoload ($class)
{
    //the filename is determined according to the class name
    $file = $class. '. php ';

    if (file_exists ($file)) {
        include $file;//Introduce PHP file
    }
}

new HelloWorld ();

/**
 * Output 

================= namespace ==================

In fact, the namespace is not a new thing, many languages (such as C + +) Early support this feature. PHP is only a late start, until PHP 5.3 before support.

A namespace is simply an identity, and its primary purpose is to resolve the problem of naming conflicts.

As in daily life, there are many people with the same name, how to distinguish these people? Then you need to add some extra markings.

It seems good to think of work units as logos, so you don't have to worry about the embarrassment of "hitting the name."

Here we do a small task, to introduce Baidu's CEO Robin Li:

namespace Baidu;

Class Li
{
    function __construct ()
    {
        echo ' Baidu founder ';
    }
}

↑ This is the basic information of Li, namespace is his unit identification, class is his name.

Namespaces are declared by keyword namespace. If a file contains namespaces, it must declare the namespace before all other code.

New Baidu Robin Li (); Qualified class name
new \ Baidu Robin Li ();//Fully qualified class name

↑ in general, whether it is introduced to others "Baidu Robin Li" or "Baidu company Robin Li", they can understand.

Qualified class names and fully qualified class names are equivalent in cases where the current namespace is not declared. Because if you do not specify a space, the default is global (\).

namespace Google;

New Baidu Robin Li (); Google Baidu Robin Li (actual results)
new Baidu Robin Li ();//Baidu Robin Li (actual results)

↑ If you introduce Robin Li to their employees at Google, be sure to indicate "Robin Li of Baidu." Otherwise he would think that Baidu is a department of Google, and Robin Li is only one of the employees.

This example shows the difference between using a qualified class name and a fully qualified class name under a namespace. (fully qualified class name = Current namespace + qualified class name)

/* Import namespaces
/use Baidu Robin Li;
New Lee

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.