Home >php教程 >PHP开发 >Analysis of namespace and use usage in php

Analysis of namespace and use usage in php

黄舟
黄舟Original
2016-12-14 10:47:471158browse

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)!


Statement:
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