Home > Backend Development > PHP Tutorial > Specific usage methods of namespace and use

Specific usage methods of namespace and use

亚连
Release: 2023-03-26 10:14:02
Original
1750 people have browsed it

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 refers to a include file that 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();
Copy after login

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();
Copy after login

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();
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template