什么是PHP名称空间?
大体上什么是名称空间?
一个外行的回答和一个例子将是伟大的。
什么是PHP名称空间?
大体上什么是名称空间?
一个外行的回答和一个例子将是伟大的。
当前回答
命名空间用于封闭一组代码,以便它们可以在不同的地方使用而不会发生名称冲突。 把它看作jQuery无冲突方法,你会更好地理解它。
其他回答
命名空间基本上允许您将代码放入容器中。这将防止使用相同名称的两个函数(以及类和变量)出现问题。
这在大型应用程序中非常有用,可以防止代码段共享相同名称的问题。
例如,假设我们需要两个名为“TheMessage”的函数。这两者都将分别打印(回显)不同的消息。 通常,这将导致语法错误,因为您不能有两个具有相同名称的函数。
要解决这个问题,可以将这些函数放到单独的名称空间中。这将允许您使用两个函数而不会出现任何错误。
您可以使用命名空间来避免您创建的代码与内部PHP类/函数/常量或第三方类/函数/常量之间的名称冲突。 命名空间还能够别名(或缩短)Extra_Long_Names,旨在减少第一个问题,提高源代码的可读性。
我们都知道,名称空间和特征在PHP中并不新鲜,但仍然有许多PHP开发人员因为它们的复杂性而不使用这些伟大的概念。 所以,在这篇文章中。我会用例子来解释清楚。 什么是名称空间和特征?
如何在代码中实现它们以使代码可重用和可扩展?
名称空间的好处
您可以使用命名空间来避免您创建的代码与内部PHP类/函数/常量或第三方类/函数/常量之间的名称冲突。
命名空间还能够别名(或缩短)Extra_Long_Names,旨在减少第一个问题,提高源代码的可读性。 让我们通过一个例子来理解名称空间。 在htdocs(xampp)或WWW (xwamp)中创建名为“php_oops”的文件夹 在根目录下创建一个名为“namespaces”的新文件夹,然后在namespaces文件夹下创建一个文件index.php。
<?php
// FilePath:- namespaces/index.php
// let's say, we have two classes in index,
// here, these two classes have global space
class A
{
function __construct()
{
echo "I am at Global space, Class A";
}
}
class B
{
function __construct()
{
echo "I am at Global space, Class B";
}
}
// now create an object of class and
$object = new A; // unqualified class name
echo "<br/>";
$object = new \B; // fully qualified class name
// output:
I am at Global space, Class A
I am at Global space, Class B
参考, https://medium.com/@akgarg007/php-laravel-namespaces-and-traits-01-9540fe2969cb
命名空间用于封闭一组代码,以便它们可以在不同的地方使用而不会发生名称冲突。 把它看作jQuery无冲突方法,你会更好地理解它。
命名空间是控制程序中名称的简单系统。 它确保名称是唯一的,不会导致任何冲突。
在其他编程语言中有一些技术,比如名称空间(比如Java中的包)。它们被用来在一个项目中拥有多个具有相同名称的类。
来自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.