namespace (hereinafter referred to as ns). After defining an ns, theclass, interface, and const (excluding variables) declared below are all in the "domain" of the declared ns. Whenrefers toainclude filethat declares ns, and if you want to call things in this ns, you must adjust the current script to this ns domain, otherwise you have to use the full name () to include it The full name of ns):
[php] view plain copy // inc.php namespace Foo; class Bar {} // 访问Foo的第一种方法,用全称 require 'inc.php'; $foo = new \Foo\Bar(); // 访问Foo的第二种方法 namespace Foo; // 调整当前脚本到Foo这个ns域,而且namespace申明必须在第一句 require 'inc.php'; $foo = new Bar();
The purpose of the use keyword is to use the alias of ns:
[php] view plain copy // 比如 use A\Very\Long\Namespace as Ns; // 这样就可以用Ns来代替A/Very/Long/Namespace这个ns下定义的东西 $foo = new Ns\Foo();
However, in some open source projects, we often see the usage of use Ns\Component without using as. This made me think about whether there is a second usage of use. The bad thing is that there is no description of this usage in the PHP documentation. I can only rely on guessing. Later, I thought about this problem carefully and came up with a more reliable one. The conclusion is that use can omit as and the following aliases and directly use the name of the last node of ns as an alias. Does it feel like the usage of the ln -s command:
[php] view plain copy // 第三种用法 require 'inc.php'; use Foo\Bar; // 这样Bar就等于Foo\Bar了 $foo = new Bar();
The above is what I compiled for everyone. The specific usage of namespace and use, I hope it will be helpful to everyone in the future.
Related articles:
Detailed usage method in PHP closure function() use()
PHP namespace Detailed usage guide for namespace and imported use
Detailed explanation of PHP Liskov substitution case
The above is the detailed content of Specific usage methods of namespace and use. For more information, please follow other related articles on the PHP Chinese website!