PHP Namespaces - Statute exploration

Exploring one: the difference between whether the namespace:

Suppose: a Application.php defined in a class Application, and namespace declaration, is as follows:

 

<?php
namespace app;

class Application
{

    protected function getClass()
    {
        return __CLASS__.PHP_EOL;
    }

}

Then use it in a test file:

<?php

require '../app/Application.php';

new Application();

 

 

Then on the error, the error probably means that the test did not find the class file

 

Uh? ! ! ! Why, I obviously quoted Application.php ah ~

 

Detective analysis time:

The first is the official document explains:

 

First of all need to recognize the role of the namespace, it is to add a location path logically (php in) to the attributes of the file, but not limited to the physical path, but the demo Why error, because Application.php that declares namespace, then you will need to follow to use it to the logical path to access a given class Application, while no longer a simple new Application, of course, the premise is still the need to introduce access to the file, the difference is, you need to use a class (here is specific categories, the method further comprising, constants, etc. may be) logical path to use it.

So how bug fixes it? There are three ways:

One:

In the demo document, the namespace declaration and namespace class Application requires declared the same, in the same logical path, can be accessed by a class Application relative logical path, as follows:

 

 

<?php
namespace app;

require '../app/Application.php';

new Application();

 

two:

Use use, to declare the use of the logical path of the file;

 

 

<?php
use app\Application;

require '../app/Application.php';

new Application();

 

three:

A logical path to call the class

 

<?php

require '../app/Application.php';

new app\Application();

So for, if I do not use the full logical path to the file, but only use the equivalent of a logical path of the directory section of Road King, what then?

which is:

 

 

<?php

use app\*;

php did not seem to support,

Here is an explanation about the use of:

 

 

For class Application we call in the demo, the complete logical path and how?

There are three cases below

 

 

<?php

require '../app/Application.php';

new app\Application();

Use OK, Application complete logical path should \ app \ Application, why? Look.

 

<?php

require '../app/Application.php';

new \app\Application();

 

这两种都没有报错,因为Application完整的逻辑路径确实为\app\Application,那么为什么第一种情况也可以呢,因为demo中并没有声明命名空间,默认为'\',第一种情况可以解释为在demo所在的命名空间下利用相对逻辑路径调用Application,所以Application完整的逻辑路径确实为\app\Application,

因此这种情况就会报错:

<?php
namespace web;

require '../app/Application.php';

new app\Application();

 

 

因为此时Application的完整逻辑路径成为了 \web\app\Application

 

官方解释如下:

 

故:在使用命名空间的时候,需要注意引用脚本的命名空间和被引用脚本的命名空间,从而使用先对逻辑路径或者绝对路径

 

发布了31 篇原创文章 · 获赞 3 · 访问量 1万+

Guess you like

Origin blog.csdn.net/qq_36557960/article/details/90340934