php 什么是命名空间?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3384204/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What are namespaces?
提问by Imran
What are PHP Namespaces?
什么是 PHP 命名空间?
What are Namespaces in general?
什么是命名空间?
A Layman answer with an example would be great.
带有示例的外行答案会很棒。
回答by cbednarski
Namespacing does for functions and classes what scope does for variables. It allows you to use the same function or class name in different parts of the same program without causing a name collision.
命名空间对函数和类的作用就像作用域对变量的作用一样。它允许您在同一程序的不同部分使用相同的函数或类名,而不会导致名称冲突。
In simple terms, think of a namespace as a person's surname. If there are two people named "John" you can use their surnames to tell them apart.
简单来说,将命名空间视为一个人的姓氏。如果有两个叫“约翰”的人,你可以用他们的姓氏来区分。
The Scenario
情景
Suppose you write an application that uses a function named output(). Your output()function takes all of the HTML code on your page and sends it to the user.
假设您编写了一个应用程序,该应用程序使用名为 的函数output()。您的output()函数获取页面上的所有 HTML 代码并将其发送给用户。
Later on your application gets bigger and you want to add new features. You add a library that allows you to generate RSS feeds. This library also uses a function named output()to output the final feed.
稍后您的应用程序会变得更大,并且您想要添加新功能。您添加了一个允许您生成 RSS 提要的库。该库还使用名为output()输出最终提要的函数。
When you call output(), how does PHP know whether to use your output()function or the RSS library's output()function? It doesn't. Unlessyou're using namespaces.
当您调用 时output(),PHP 如何知道是使用您的output()函数还是使用 RSS 库的output()函数?它没有。 除非您使用命名空间。
Example
例子
How do we solve having two output()functions? Simple. We stick each output()function in its own namespace.
我们如何解决有两个output()函数?简单的。我们将每个output()函数放在自己的命名空间中。
That would look something like this:
这看起来像这样:
namespace MyProject;
function output() {
# Output HTML page
echo 'HTML!';
}
namespace RSSLibrary;
function output(){
# Output RSS feed
echo 'RSS!';
}
Later when we want to use the different functions, we'd use:
稍后当我们想要使用不同的功能时,我们会使用:
\MyProject\output();
\RSSLibrary\output();
Or we can declare that we're in one of the namespaces and then we can just call that namespace's output():
或者我们可以声明我们在其中一个命名空间中,然后我们可以调用该命名空间的output():
namespace MyProject;
output(); # Output HTML page
\RSSLibrary\output();
No Namespaces?
没有命名空间?
If we didn't have namespaces we'd have to (potentially) change a lot of code any time we added a library, or come up with tedious prefixes to make our function names unique. With namespaces, we can avoid the headache of naming collisions when mixing third-party code with our own projects.
如果我们没有命名空间,我们将不得不(可能)在我们添加库时更改大量代码,或者想出乏味的前缀来使我们的函数名称唯一。使用命名空间,我们可以避免在将第三方代码与我们自己的项目混合时出现的命名冲突问题。
回答by alex
A namespace allows you to place a bunch of code under a name and not have any naming conflicts with classes, functions and constants.
命名空间允许您将一堆代码放在一个名称下,并且不会与类、函数和常量发生任何命名冲突。
It allows your code to livein that namespace.
它允许您的代码存在于该命名空间中。
PHP uses the somewhat controversial character\to show namespace levels. People got up in arms because it is also used as an escape character.
PHP 使用有点争议的字符\来显示命名空间级别。人们起身武装,因为它也被用作逃避角色。
To use the namespace in PHP, use something like this at the top of your file.
要在 PHP 中使用命名空间,请在文件顶部使用类似的内容。
namespace my\namespace;
You can find a lot more information on the official PHP documentation for namespaces.
您可以在有关命名空间的官方 PHP 文档中找到更多信息。
回答by Bahman.A
Since it's easier to learn about the keyword “use” by knowing about “namespace”, let me explain namespace first by looking at a basic Laravel project.
由于通过了解“命名空间”更容易了解关键字“使用”,让我先通过查看一个基本的 Laravel 项目来解释命名空间。
There is a controller class with the name: Controller.phpwhich is in the path: app/Http/Controllersfrom the project's root directory There is also another controller class named: Controller.php, but this one is in the path: vendor/laravel/framework/src/Illuminate/Routingfrom the project's root directory
有一个名为:Controller.php的控制器类,它位于项目根目录的路径: app/Http/Controllers还有另一个名为:Controller.php 的控制器类,但这个在路径: vendor/ laravel/framework/src/Illuminate/Routing来自项目根目录
You don't need to look at the source code yet if you're new to php because it can confuse you, instead let me explain to you the part of it that we care about and will help us understand “namespace” and “use”.
如果您是 php 新手,您还不需要查看源代码,因为它会使您感到困惑,而是让我向您解释我们关心的部分,这将有助于我们理解“命名空间”和“使用”。
So as a matter of fact, our first controller class: app/Http/Controllers/Controller.phpneeds to use the Second controller class vendor/laravel/framework/src/Illuminate/Routing/Controller.php. it actually needs to extend this Class in order to have access to its content for handling some crucial routing functionalities.
所以事实上,我们的第一个控制器类: app/Http/Controllers/Controller.php需要使用第二个控制器类vendor/laravel/framework/src/Illuminate/Routing/Controller.php。它实际上需要扩展这个类才能访问它的内容来处理一些关键的路由功能。
So how can a class extend another class that has the same name?class Controller extends Controller? this will NOT work,unless there is a way to distinguish these two classesand that's where namespacecomes handy and the usekeyword
helps to complete the mission of, allowing the usage of; (classes; methods; interfaces and constants), with the same name, in the same scope.
那么一个类如何扩展另一个具有相同名称的类呢?class Controller extends Controller? 这是行不通的,除非有办法区分这两个类并且这namespace很方便并且use关键字有助于完成任务,允许使用;(类;方法;接口和常量),具有相同的名称,在相同的范围内。
now how is it done in the code? very simple!if we look at app/Http/Controllers/Controller.phpsource code, we can see at the top of the class
namespace is declared as: namespace App\Http\Controllers, so this is how you give your class a namespace so it can be referenced by other classes
now this looks the same as the path to this class from the project's root directory, with little difference and that's the usage of “\” instead of “/“
(same as command prompt in windows),
but there is another difference and that's the App with capital ‘A' in the namespace versus ‘app' with
Lowercase ‘a' in the path. Also note that namespace is case-sensitive.
现在它是如何在代码中完成的?很简单!如果我们查看app/Http/Controllers/Controller.php源代码,我们可以看到在类命名空间的顶部声明为:namespace App\Http\Controllers,所以这就是你如何给你的类一个命名空间,以便它现在可以被其他类引用这看起来和从项目根目录到这个类的路径一样,几乎没有区别,就是使用“\”而不是“/”
(与windows中的命令提示符相同),但还有另一个区别,那就是大写的App命名空间中的“A”与路径中带有小写“a”的“app”。另请注意,命名空间区分大小写。
So namespace is a separate concept than the path, it can follow the path structure if it helps but it doesn't have to be exact path to the class, method, interfaces or constantsfor example take a look at: vendor/laravel/framework/src/Illuminate/Routing/Controller.phpsource code,
所以命名空间是一个与路径不同的概念,如果有帮助,它可以遵循路径结构,但它不必是类、方法、接口或常量的确切路径,例如看看: vendor/laravel/framework /src/Illuminate/Routing/Controller.php源代码,
we see at the top of the class the namespace is declared as: Illuminate\Routing
我们在类的顶部看到命名空间被声明为: Illuminate\Routing
now let's take look at the “use” keyword,
we use, the “use” keyword to make our class aware of a specific class or function that we want to use in our class
现在让我们看看“ use”关键字,我们使用“ use”关键字让我们的类知道我们想要在我们的类中使用的特定类或函数
so we are not importing or including anythingwe're just letting our class know that we will be using a specific class or
method by referencing them by their namespace
let's take a look at app/Http/Controllers/Controller.phpsource code,
as you can see from the line: “use Illuminate\Routing\Controller as BaseController”, the “use” keyword followed by namespacefor the target class
(note that Illuminate\Routing\Controller.php and Illuminate\Routing\Controller ‘without .php extension' are interchangeable)
所以我们没有导入或包含任何我们只是让我们的类知道我们将通过命名空间引用它们来使用特定的类或方法让我们看看app/Http/Controllers/Controller.php源代码,如你可以从这一行看到:“ use Illuminate\Routing\Controller as BaseController”,“ use”关键字后跟
目标类的命名空间(注意 Illuminate\Routing\Controller.php 和 Illuminate\Routing\Controller 'without .php extension' 是可以互换的)
we can use the “as” keyword along with the “use” keyword to give a specific class, method, interfaces or constantsan alias which allows
app/Http/Controllers/Controller.phpto extend Illuminate\Routing\Controller.phpas BaseController in the line:
“class Controller extends BaseController”.
我们可以使用“ as”关键字和“ use”关键字给特定的类、方法、接口或常量一个别名,允许
app/Http/Controllers/Controller.php将Illuminate\Routing\Controller.php扩展为 BaseController行:“ class Controller extends BaseController”。
回答by 2ndkauboy
There are techniques like namespaces in other programming languages (like packages in Java). They are used to be able to have mutliple classes with the same name wihtin a project.
其他编程语言(如 Java 中的包)中也有类似命名空间的技术。它们习惯于能够在一个项目中拥有多个同名的类。
From the php documentation (http://www.php.net/manual/en/language.namespaces.rationale.php):
从 php 文档(http://www.php.net/manual/en/language.namespaces.rationale.php):
What are namespaces? In the broadest definition namespaces are a way of encapsulating items. This can be seen as an abstract concept in many places. For example, in any operating system directories serve to group related files, and act as a namespace for the files within them. As a concrete example, the file foo.txt can exist in both directory /home/greg and in /home/other, but two copies of foo.txt cannot co-exist in the same directory. In addition, to access the foo.txt file outside of the /home/greg directory, we must prepend the directory name to the file name using the directory separator to get /home/greg/foo.txt. This same principle extends to namespaces in the programming world.
什么是命名空间?在最广泛的定义中,命名空间是封装项目的一种方式。这在很多地方都可以看作是一个抽象的概念。例如,在任何操作系统中,目录都用于对相关文件进行分组,并充当其中文件的命名空间。作为一个具体的例子,文件 foo.txt 可以同时存在于目录 /home/greg 和 /home/other 中,但是 foo.txt 的两个副本不能共存于同一目录中。此外,要访问 /home/greg 目录之外的 foo.txt 文件,我们必须使用目录分隔符将目录名添加到文件名中,以获取 /home/greg/foo.txt。同样的原则扩展到编程世界中的命名空间。
回答by 2ndkauboy
Much like directoriesand files, namespace in PHP serves to group classes, functions, interfacesand constants.
很像目录和文件,PHP 中的命名空间用于对类、函数、接口和常量进行分组。
Example:
例子:
Filesystem | PHP Namespace
----------------|------------------
/Dir/File.txt | \Namespace\Class
It provides a way of wrapping items from the global space and allows use of plain item name without causing name collision in a program. It's supported in PHP 5.3.0, PHP 7.
它提供了一种从全局空间包装项目的方法,并允许使用简单的项目名称而不会在程序中引起名称冲突。它在 PHP 5.3.0、PHP 7 中受支持。
But there are some limits in analogy between PHP namespace and Unix based filesystem:
但是 PHP 命名空间和基于 Unix 的文件系统之间的类比存在一些限制:
| Filesystem | PHP Namespace
--------------------------|-----------------------|-------------------------
Cas sensitive | No | Yes
--------------------------|-----------------------|-------------------------
Name with plain number | Yes | No
--------------------------|-----------------------|-------------------------
Path level | Yes | Yes
--------------------------|-----------------------|-------------------------
Plain metacharacters name | Yes | No
The principle extends to namespace in programming word.
该原则扩展到编程词中的命名空间。
回答by Mamun Sabuj
Namespace is like packaging many things into a single pack. Imagine a namespace as a drawer in which you can put all kinds of things: a pencil, a ruler, a piece of paper and so forth. To avoid using each other's items, you decide to label the drawers so it's clear what belongs to whom.
命名空间就像将许多东西打包成一个包。把命名空间想象成一个抽屉,你可以在里面放各种各样的东西:铅笔、尺子、一张纸等等。为了避免使用彼此的物品,您决定在抽屉上贴上标签,以便清楚哪些物品属于谁。
回答by staticsan
A Namespace works like a directory. You know how you can put files in a directory with the same names as files in the parent (or any other) directory? Well, a namespace lets you do that within an application for variables, functions and classes.
命名空间的工作方式类似于目录。您知道如何将文件放入与父(或任何其他)目录中的文件同名的目录中吗?好吧,命名空间允许您在应用程序中为变量、函数和类执行此操作。
There was a bit of a trend in PHP a little while ago for huge classes of static functions. The only way to call any of those functions was by prefixing a call with the class name. This was a primitive attempt at namespaces, but with not very much of the benefits.
不久前,PHP 中出现了一些关于大量静态函数类的趋势。调用任何这些函数的唯一方法是在调用前加上类名。这是对命名空间的原始尝试,但没有太多好处。
回答by Alexander
A namespace basically lets you put code into a container. This will prevent problems with two functions (as well as classes and variables) that share the same name.
命名空间基本上允许您将代码放入容器中。这将防止共享相同名称的两个函数(以及类和变量)出现问题。
These are useful when working when larger applications to prevent issues with pieces of code sharing the same name.
这些在较大的应用程序中工作时非常有用,可以防止共享相同名称的代码段出现问题。
For example, lets say we wanted two functions called "TheMessage" . These both would print (echo) different messages each. Normally, this would cause a syntax error, as you cannot have two functions that share the same name.
例如,假设我们想要两个名为 "TheMessage" 的函数。这两者都会打印(回显)不同的消息。通常,这会导致语法错误,因为您不能有两个共享相同名称的函数。
To fix this, you could put these functions into separate namespaces. This would allow you to use both functions without any errors.
要解决此问题,您可以将这些函数放入单独的命名空间中。这将允许您使用这两个功能而不会出现任何错误。
回答by Emmanuel David
Namespace is used to enclosed group of codes so that they can be used in different places without name conflicts. Think about this as jQuery no conflict method and you will understand it better.
命名空间用于封闭一组代码,以便它们可以在不同的地方使用而不会发生名称冲突。将此视为 jQuery 无冲突方法,您会更好地理解它。
回答by humaid
A namespace is a simple system to control the names in a program.
It ensures that names are unique and won't lead to any conflict.
命名空间是一个简单的系统,用于控制程序中的名称。
它确保名称是唯一的,不会导致任何冲突。

