Introduction to namespace

Time:2021-1-14

The function is to solve the conflict of referencing the same named class, function and constant in different files

Let’s start with an example

<?php
namespace my\name; //Refer to the section defining a namespace

class MyClass {}
function myfunction() {}
const MYCONST = 1;

$a = new MyClass;
$c = new \my\name\MyClass; //Refer to the global space section

$a = strlen('hi'); //Refer to the section "using namespace: fallback global functions / constants"

$d = namespace\MYCONST; //Refer to "namespace operators and"__ NAMESPACE__ Constant "section

$d = __NAMESPACE__ . '\MYCONST';
echo constant($d); //Refer to the "namespace and dynamic language features" section

The above is a comprehensive example, which will be explained one by one

  1. Declare a namespace. It’s very simple. At the top of all the code, writenamespace xxx\yyy;At this time, the following code is in the virtual space of XXX / YYY;

  2. Subnamespacenamespace MyProject\Sub\Level;According to psr4 standard, the level of namespace should be divided according to the directory structure, such as app / HTTP / model/ User.php , whose namespace isnamespace App\Http\Model;

  3. Multiple namespace can be used in a script file, but it is not recommended, so it is not explained here;

  4. How do you know which namespace the classes, functions and constants are currently used in PHP?

    Let’s start with a simple example

    demo2.php

     <?php
     namespace x\z;
    
     class demo{}

    demo1.php

     <?php
     namespace x\y;
     include './demo2.php';
    
     class demo{}
     $obj = new demo;    //Unqualified name - access the X / Y / demo class
     var_dump($obj);        //object(x\y\demo)#1 (0) { }

    What if you want to visit the demo class in demo2. PHP? Write like this$obj = new x\z\demo;It’s a mistake,

    The mistake isFatal error: Uncaught Error: Class 'x\y\x\z\demo' not found

    As you can see, it is identified asx\y\x\z\demoThis is actually a qualified name;

    It can be accessed directly with a fully qualified name\x\z\demo

    Of course, there is another access method, use, as follows:

     namespace x\y;
     include './demo2.php';
     use x\z as c;
    
     class demo{}
     $obj = new c\demo;
     var_dump($obj);        //object(x\z\demo)#1 (0) { }

    Summary: you can see that to access elements in a namespace, you can use unrestricted, qualified, fully qualified and other methods. Unrestricted generally refers to the current namespace, qualified refers to the child namespace under the current namespace, and qualified directly refers to a certain namespace,

    Another case is that when using unrestricted, if the current namespace can’t find the function / constant to be accessed, it will find it in the global; class can’t; class must be added\

    Of course, the use of use is a little different. I will continue to explain it later;

  5. The namespace is also influenced by the dynamic semantics of PHP

    what do you mean? I don’t understand either. Let’s take an example

    example1.php:

     <?php
     class classname{}
     function funcname(){}
     const constname = "global";
     ?>

    example2.php:

     <?php
     namespace namespacename;
     class classname{}
     function funcname(){}
     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
    
     /* 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\funcname
     echo constant('\namespacename\constname'), "\n"; // prints namespaced
     echo constant('namespacename\constname'), "\n"; // also prints namespaced
     ?>

    As you can see, this method is equivalent to the previous default with global\Just remember that;

  6. namespaceKeywords and__NAMESPACE__constant

    It refers to the name of the current namespace and can access the elements inside the current namespace abstractly;__NAMESPACE__Is a string of namespace names

    Note that in global space,_NAMESPACE__Is a null character

Although the two meanings are similar, the actual use is still different. The following are examples of their respective use:

_NAMESPACE__Dynamic creation name

file2.php

<?php
namespace MyProject\file2;

class name{}

file1.php

    <?php
    namespace MyProject;
    include './file2.php';

    class name{}

    function get($classname)
    {
        $a = __NAMESPACE__ . '\' . $classname;
        return new $a;
    }

    $obj = get('file2\name');    //object(MyProject\file2\name)#1 (0) { }
    //$obji2 = new myproject / File2 / name; / / an error will be reported, which will be parsed as' myproject / myproject / File2 / name '
    $obj3 = get('name');    // object(MyProject\name)#2 (0) { }
    var_dump($obj, $obj2, $obj3);

keywordnamespaceCan be used to explicitly access elements in the current namespace or subnamespace

<?php
namespace MyProject;

use blah\blah as mine;         //The alias mine refers to blah

blah\mine();                 //Myproject / blah / mine() function

namespace\blah\mine();         //Myproject / blah / mine() function

namespace\func();             // MyProject\func()

namespace\sub\func();         // MyProject\sub\func()

namespace\cname::method();     //Static method () of myproject / CNAME class

$a = new namespace\sub\cname();     // MyProject\sub\cname

$b = namespace\CONSTANT;             // MyProject\CONSTANT
?>
<?php
//Global space
namespace\func();                     //Func ()

namespace\sub\func();                 // sub\func()

namespace\cname::method();             //Method () of the CNAME class in the global context;

$a = new namespace\sub\cname();     // sub\cname

$b = namespace\CONSTANT;             //Global constant
?>
  1. Alias use

    First of all, through the previous learning, we can know that in a namespace, if you want to use elements in other namespace, you must use fully qualified method, which will lead to long identifier and poor readability when importing, such as\App\Http\Controller\UserCenter;Therefore, the alias mechanism is introduced;

Using use to introduce a namespace will automatically bring the global\For exampleuse Foo,use Foo\BarActually\Foo,\Foo\BarOtherwise, it has no meaning;

In addition, use has an alias by default. For example, it is the above one. In fact, it isFoo as Foo , Foo\Bar as Bar

Of course, it can also be customizeduse Foo\Bar as B

Let’s start with a simple example

file2.php

<?php
namespace b;
class demo{}

file3.php

<?php
namespace a\b\c;
class demo{}

file1.php

<?php
namespace a;
include './file2.php';
include './file3.php';
class demo{}

$obj = new b\demo;        //This access to the A / B / demo does not exist and an error is reported
$obj2 = new a\b\c\demo;    //It is resolved as a / A / B / C / demo and does not exist. An error is reported
var_dump($obj);

-----------

namespace a;
include './file2.php';
include './file3.php';
class demo{}
use b;  //Equivalent to use as B;
use a\b\c as file3;

$obj = new b\demo;        //object(b\demo)#1 (0) { }
$obj2 = new file3\demo;    //object(a\b\c\demo)#2 (0) { }
var_dump($obj, $obj2);    

Here are some examples of use

<?php
namespace foo;
use My\Full\Classname as Another;            //Give a namespace an alias


use My\Full\NSname;                            //Same as use my full nsname as nsname


use ArrayObject;                            //Import a global class


use function My\Full\functionName;            //Introduce a function of my / full / functionname


use function My\Full\functionName as func;    //Function alias


use const My\Full\CONSTANT;                    //Introduce a constant


$obj = new namespace\Another;                 //Instantiate foo / another object

$obj = new Another;                         //Instantiate my / full / classname object

NSname\subns\func();                         //Call the function my / full / nsname / subns / func

$a = new ArrayObject(array(1));             //Instantiate arrayobject object
//If you do not use "use / arrayobject", instantiate a foo / arrayobject object


func();                                     // My\Full\functionName

echo CONSTANT;                                 // My\Full\CONSTANT
?>

To simplify the operation, PHP also supports multiple use statements in one line

<?php
use My\Full\Classname as Another, My\Full\NSname;

$obj = new Another; //Instantiate my / full / classname object
NSname\subns\func(); //Call the function my / full / nsname / subns / func
?>

Import and dynamic names

<?php
use My\Full\Classname as Another, My\Full\NSname;

$obj = new Another; //Instantiate a my full classname object
$a = 'Another';
$obj = new $a;      //Materialize an another object
?>

In addition, the import operation affects only unqualified and qualified names. Fully qualified names are not affected by import because they are deterministic.

<?php
use My\Full\Classname as Another, My\Full\NSname;

$obj = new Another; // instantiates object of class My\Full\Classname
$obj = new \Another; // instantiates object of class Another
$obj = new Another\thing; // instantiates object of class My\Full\Classname\thing
$obj = new \Another\thing; // instantiates object of class Another\thing
?>
  1. Global space\

    If no namespace is defined, all classes and functions are defined in global space, just like before PHP introduced the concept of namespace. Prefix the name\Indicates that the name is a name in global space, even if it is in another namespace.
<?php
namespace A\B\C;

/*This function is a / B / C / fopen*/
function fopen() { 
     /* ... */
     $f = \fopen(...); //Call global fopen function
     return $f;
} 
?>
  1. Backup global function / constant

    When using an unqualified class, function, or constant name in a namespace, the class name always resolves to the name in the current namespace. Therefore, when accessing class names inside the system or not contained in the namespace, you must use fully qualified names, such as:
<?php
namespace A\B\C;
class Exception extends \Exception {}

$a = new Exception('hi'); //$a is an object of class A / B / C / exception
$b = new \Exception('hi'); //$B is an object of the class exception

$c = new ArrayObject; //Fatal error, unable to find class A / B / C / arrayobject
?>

For functions and constants, if the function or constant does not exist in the current namespace, PHP will use the function or constant in global space instead

<?php
namespace A\B\C;

const E_ERROR = 45;
function strlen($str)
{
    return \strlen($str) - 1;
}

echo E_ERROR, "\n"; //Output "45"
echo INI_ALL, "\n"; //Output "7" - use global constant ini_ ALL

echo strlen('hi'), "\n"; //Output "1"
if (is_array('hi')) { //Output "is not array"
    echo "is array\n";
} else {
    echo "is not array\n";
}
?>

This work adoptsCC agreementReprint must indicate the author and the link of this article


The wind in June