The examples in this article describe the usage of namespace and use in php. Share it with everyone for your reference, the details are as follows:
namespace (hereinafter referred to as ns). After defining an ns, the class, interface, and const (excluding variables) declared below are all in the "domain" of the declared ns. When referencing an include file that declares ns, and if you want to call something in this ns, you must adjust the current script to the ns domain, otherwise you have to use the full name () to include the full name of ns):
// 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();
use The purpose of the keyword is to use the alias of ns:
// 比如 use A\Very\Long\Namespace as Ns; // 这样就可以用Ns来代替A/Very/Long/Namespace这个ns下定义的东西 $foo = new Ns\Foo();
But you often see use in some open source projects This usage of NsComponent does not use as, which 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, so I can only rely on guessing. Later I thought about this carefully. Question, a more reliable 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 ln? How to use the -s command:
// 第三种用法 require 'inc.php'; use Foo\Bar; // 这样Bar就等于Foo\Bar了 $foo = new Bar();
I hope this article will be helpful to everyone in PHP programming. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!