Table of Contents
定义命名空间" >定义命名空间
定义子命名空间" >定义子命名空间
在同一个文件中定义多个命名空间" >在同一个文件中定义多个命名空间
使用命名空间" >使用命名空间
命名空间和动态语言特征" >命名空间和动态语言特征
namespace关键字和NAMESPACE常量" >namespace关键字和NAMESPACE常量
Home Backend Development PHP Tutorial A little personal understanding of namespaces

A little personal understanding of namespaces

Sep 08, 2020 pm 01:12 PM
Namespaces

A little personal understanding of namespaces

相关学习推荐:php编程(视频)

一直对PHP的命名空间没有全面的了解,只知道是一种可以避免命名冲突的语法结构或特性,下面是我在PHP官网结合实际操作上,来帮助自己理解namespace;
如果有不对的地方,欢迎大家来纠正,谢谢各位大佬!

来源

命名空间是一种抽象的分层,或者说封装的概念;比如文件系统中,hello.php可以在/www/a/和/www/b/两个目录其下存在,但是不能在一个目录下,有两个相同的hello.php;

其次,www/a/ 下可以直接访问到hello.php,但是在a外面的其他目录中,直接访问hello.php,是出错的,因为系统并不知道要访问的文件就是www/a/hello.php;必须得加上一个指定的路径,绝对,相对路径都行;命名空间就借鉴了这种逻辑概念;

为什么说是逻辑概念?因为文件系统本身也是一种虚拟的,抽象的,实际的磁盘是分为n个block块,是没有直接的这种目录结构概念

解决的问题

  1. 自己写的代码中,与PHP内置(或第三方)的类,函数,常量 之间的命名冲突;
    比如说, 载入一个redis的DB类,但是又自己写了一个mysql的DB类,此时,类名相同,必然产生冲突,此时如果将两个类划分到不同的命名空间中,比如 DB\redis\connClass , DB\mysql\connClass,则避免了这种问题
  2. 为很长的名称创建别名,提高代码可读性;
    比如说,一个类名是UserInformationCenter,假如命名空间在 App\Controller\,那么使用时,要写 App\Controller\UserInformationCenter ,不利于可读性,因此可以加一个简短的别名,App\Controller\UserInformationCenter as UIC;
# 使用示例namespace my\name; //声明一个命名空间,下面的代码属于这个命名空间内class MyClass {} //实际 : my\name\Myclass{}function myfunction() {} // my\name\myfunction()const MYCONST = 1; // my\name\MYCONST$a = new MyClass; //实例化的类是 my\name\Myclass{}$b = new \my\name\MyClass; //object(my\name\MyClass)#2 (0) {}$c = strlen(&#39;hi&#39;);    //全局空间下,前面省略了 \$d = namespace\MYCONST;        //namespace关键字获取的就是当前的命名空间名称$e = __NAMESPACE__ . "\MYCONST";echo "<pre class="brush:php;toolbar:false">";var_dump($a, $b, $c ,$d ,$e);echo constant($e);/*object(my\name\MyClass)#1 (0) {
}
object(my\name\MyClass)#2 (0) {
}
int(2)
int(1)
string(15) "my\name\MYCONST"
1
*/
Copy after login

注意:名为PHP或php的命名空间,以及以这些名字开头的命名空间(例如PHP\Classes)被保留用作语言内核使用,而不应该在用户空间的代码中使用。

虽然任意合法的PHP代码都可以包含在命名空间中,但只有以下类型的代码受命名空间的影响,它们是:类(包括抽象类和traits)、接口、函数和常量。

命名空间通过关键字namespace 来声明。如果一个文件中包含命名空间,它必须在其它所有代码之前声明命名空间,除了一个以外:declare关键字。

namespace MyProject;const CONNECT_OK = 1;class Connection { /* ... */ }function connect() { /* ... */  }
Copy after login
namespace MyProject\Sub\Level;const CONNECT_OK = 1;    //MyProject\Sub\Level\CONNECT_OKclass Connection { /* ... */ }        //MyProject\Sub\Level\Connectionfunction connect() { /* ... */  }    //MyProject\Sub\Level\connect
Copy after login
  1. 写法1
namespace MyProject;const CONNECT_OK = 1;class Connection { /* ... */ }function connect() { /* ... */  }namespace AnotherProject;const CONNECT_OK = 1;class Connection { /* ... */ }function connect() { /* ... */  }
Copy after login
  1. 写法2
namespace MyProject {const CONNECT_OK = 1;class Connection { /* ... */ }function connect() { /* ... */  }}namespace AnotherProject {const CONNECT_OK = 1;class Connection { /* ... */ }function connect() { /* ... */  }}
Copy after login
  1. 非限定名称,或不包含前缀的类名称,例如 $a=new foo();foo::staticmethod();。如果当前命名空间是 currentnamespace,foo 将被解析为 currentnamespace\foo。如果使用 foo 的代码是全局的,不包含在任何命名空间中的代码,则 foo 会被解析为foo。 警告:如果命名空间中的函数或常量未定义,则该非限定的函数名称或常量名称会被解析为全局函数名称或常量名称
  2. 限定名称,或包含前缀的名称,例如 $a = new subnamespace\foo();subnamespace\foo::staticmethod();。如果当前的命名空间是 currentnamespace,则 foo 会被解析为 currentnamespace\subnamespace\foo。如果使用 foo 的代码是全局的,不包含在任何命名空间中的代码,foo 会被解析为subnamespace\foo
  3. 完全限定名称,或包含了全局前缀操作符的名称,例如, $a = new \currentnamespace\foo();\currentnamespace\foo::staticmethod();。在这种情况下,foo 总是被解析为代码中的文字名(literal name)currentnamespace\foo

下面是示例:

# file1.php<?phpnamespace Foo\Bar\subnamespace;const FOO = 1;function foo() {}class foo{
    static function staticmethod() {}}?># file2.php<?phpnamespace Foo\Bar;include &#39;file1.php&#39;;const FOO = 2;function foo() {}class foo{
    static function staticmethod() {}}/* 非限定名称 */foo();                     // 解析为 function Foo\Bar\foofoo::staticmethod();     // 解析为类 Foo\Bar\foo的静态方法staticmethodecho FOO;                 // 解析为 constant Foo\Bar\FOO/* 限定名称 */subnamespace\foo();                 // 解析为函数 Foo\Bar\subnamespace\foosubnamespace\foo::staticmethod();     // 解析为类 Foo\Bar\subnamespace\foo , 以及类的方法 staticmethodecho subnamespace\FOO;                 // 解析为常量 Foo\Bar\subnamespace\FOO/* 完全限定名称 */\Foo\Bar\foo();                 // 解析为函数 Foo\Bar\foo\Foo\Bar\foo::staticmethod();     // 解析为类 Foo\Bar\foo, 以及类的方法 staticmethodecho \Foo\Bar\FOO;                 // 解析为常量 Foo\Bar\FOO?>
Copy after login

注意访问任意全局类、函数或常量,都可以使用完全限定名称,例如 \strlen()\Exception\INI_ALL

<?phpnamespace Foo;function strlen() {}const INI_ALL = 3;class Exception {}$a = \strlen(&#39;hi&#39;);             // 调用全局函数strlen  2$b = \INI_ALL;                     // 访问全局常量 INI_ALL  7$c = new \Exception(&#39;error&#39;);     // 实例化全局类 Exception?>
Copy after login

example1.php:

<?phpclass classname{
    function __construct()
    {
        echo __METHOD__,"\n";
    }}function funcname(){
    echo __FUNCTION__,"\n";}const constname = "global";$a = &#39;classname&#39;;$obj = new $a;         // classname::__construct$b = &#39;funcname&#39;;$b();                 // funcnameecho constant(&#39;constname&#39;), "\n";     // global?>
Copy after login
<?phpnamespace namespacename;class classname{
    function __construct()
    {
        echo __METHOD__,"\n";
    }}function funcname(){
    echo __FUNCTION__,"\n";}const constname = "namespaced";include &#39;example1.php&#39;;$a = &#39;classname&#39;;$obj = new $a;         //  classname::__construct$b = &#39;funcname&#39;;$b(); // prints funcnameecho constant(&#39;constname&#39;), "\n"; // prints global/* note that if using double quotes, "\\namespacename\\classname" must be used */$a = &#39;\namespacename\classname&#39;;$obj = new $a; // prints namespacename\classname::__construct$a = &#39;namespacename\classname&#39;;$obj = new $a; // also prints namespacename\classname::__construct$b = &#39;namespacename\funcname&#39;;$b(); // prints namespacename\funcname$b = &#39;\namespacename\funcname&#39;;$b(); // also prints namespacename\funcnameecho constant(&#39;\namespacename\constname&#39;), "\n"; // prints namespacedecho constant(&#39;namespacename\constname&#39;), "\n"; // also prints namespaced?>
Copy after login

PHP支持两种抽象的访问当前命名空间内部元素的方法,__NAMESPACE__ 魔术常量和namespace关键字。

常量__NAMESPACE__的值是包含当前命名空间名称的字符串。在全局的,不包括在任何命名空间中的代码,它包含一个空的字符串。

常量 __NAMESPACE__ 在动态创建名称时很有用,例如:

<?phpnamespace MyProject;function get($classname){
    $a = __NAMESPACE__ . &#39;\\&#39; . $classname;
    return new $a;}?>
Copy after login

关键字 namespace 可用来显式访问当前命名空间或子命名空间中的元素。它等价于类中的 self 操作符。

<?phpnamespace MyProject;use blah\blah as mine;blah\mine();             // MyProject\blah\mine()namespace\blah\mine();     // MyProject\blah\mine()namespace\func();             // MyProject\func()namespace\sub\func();         // MyProject\sub\func()namespace\cname::method();     // MyProject\cname::method()$a = new namespace\sub\cname();     // MyProject\sub\cname$b = namespace\CONSTANT;             // MyProject\CONSTANT?>
Copy after login

使用命名空间:别名/导入

为类名称使用别名,为接口使用别名,为命名空间名称使用别名,别名是通过操作符 use 来实现的

想了解更多编程学习,敬请关注php培训栏目!

The above is the detailed content of A little personal understanding of namespaces. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Solve PHP error: The specified namespace class was not found Solve PHP error: The specified namespace class was not found Aug 18, 2023 pm 11:28 PM

Solve PHP error: The specified namespace class was not found. When developing using PHP, we often encounter various error messages. One of the common errors is "The specified namespace class was not found". This error is usually caused by the imported class file not being properly namespace referenced. This article explains how to solve this problem and provides some code examples. First, let’s take a look at an example of a common error message: Fatalerror:UncaughtError:C

How to use namespace in F3 framework? How to use namespace in F3 framework? Jun 03, 2023 am 08:02 AM

The F3 framework is a simple, easy-to-use, flexible and scalable PHPWeb framework. Its namespace (Namespace) mechanism provides us with a more standardized, more readable, and clearer code structure. In this article, we will explore how to use namespaces in the F3 framework. 1. What is a namespace? Namespaces are often used to solve the problem of naming conflicts in PHP. It can encapsulate one or more classes, functions or constants in a namespace, which is equivalent to adding a prefix to them. example

Design ideas and implementation methods of Redis namespace and expiration mechanism Design ideas and implementation methods of Redis namespace and expiration mechanism May 11, 2023 am 10:40 AM

Redis is an open source, high-performance key-value storage database. When using Redis for data storage, we need to consider the design of the key namespace and expiration mechanism to maintain Redis performance and data integrity. This article will introduce the design ideas and implementation methods of Redis' namespace and expiration mechanism. 1. Redis namespace design ideas In Redis, keys can be set arbitrarily. In order to facilitate the management and distinction of different data types, Redis introduces the concept of namespace. Life

C++ syntax error: undefined namespace used, how to deal with it? C++ syntax error: undefined namespace used, how to deal with it? Aug 21, 2023 pm 09:49 PM

C++ is a widely used high-level programming language. It has high flexibility and scalability, but it also requires developers to strictly master its grammatical rules to avoid errors. One of the common errors is "use of undefined namespace". This article explains what this error means, why it occurs, and how to fix it. 1. What is the use of undefined namespace? In C++, namespaces are a way of organizing reusable code in order to keep it modular and readable. You can use namespaces to make functions with the same name

Example of new features in PHP8: How to use namespaces and codes to better organize the code structure? Example of new features in PHP8: How to use namespaces and codes to better organize the code structure? Sep 11, 2023 pm 12:22 PM

Example of new features in PHP8: How to use namespaces and codes to better organize the code structure? Introduction: PHP8 is an important version of the PHP programming language, which introduces many exciting new features and improvements. One of the most important new features is namespaces. Namespaces are a way to organize your code into a better structure that avoids conflicts between classes, functions, and constants with the same name. In this article, we’ll look at how to leverage namespaces and codes to better structure your PHP8 code

PHP 5.3 new feature: How to use namespaces to resolve class name conflicts PHP 5.3 new feature: How to use namespaces to resolve class name conflicts Jul 30, 2023 pm 12:25 PM

New features of PHP5.3: How to use namespaces to solve class name conflicts Introduction: During the development of PHP, as projects become larger and more complex, class name conflicts also arise. In order to solve this problem, PHP5.3 version introduced the concept of namespace. Namespaces provide a way to organize related classes, functions, and constants together to avoid naming conflicts. This article will introduce in detail the concept of PHP namespaces and how to use namespaces to solve class name conflicts, with code examples.

Best practices for PHP autoloading: ensuring stability and performance Best practices for PHP autoloading: ensuring stability and performance Mar 02, 2024 pm 09:10 PM

PHP Autoloading Overview Autoloading is a mechanism for automatically loading classes and their dependencies before use. In PHP, this is achieved by using the __autoload() function or an autoloader such as Composer. Proper autoloading settings are critical to ensuring the stability and performance of your codebase. PSR-4 automatic loading standard PSR-4 is the automatic loading standard defined by PHP-FIG. It is based on namespace and directory structure conventions to simplify class file lookup. To comply with PSR-4: define a root namespace (e.g. MyApp). Use backslash() as namespace separator. Use lowercase letters to represent namespace elements. Create a corresponding directory for each namespace element. General essay

Methods to solve PHP namespace errors and generate corresponding error prompts Methods to solve PHP namespace errors and generate corresponding error prompts Aug 07, 2023 pm 05:16 PM

How to resolve PHP namespace errors and generate corresponding error messages. PHP is a widely used server-side scripting language that is used to develop web applications. In PHP, namespace (Namespace) is a mechanism for managing and organizing code, which can avoid naming conflicts and improve code readability and maintainability. However, the complexity of namespace definition and use sometimes leads to errors. This article will introduce some methods to solve PHP namespace errors and generate corresponding error prompts. 1. Name space

See all articles