PHP Velho Oeste 2024

提示

要写出能经受住时间考验的代码,建议在全局的命名空间中,尽量不要用变量、函数或类名,以避免与其它用户空间代码出现命名空间冲突。

防止函数和类的命名冲突的一个常见方法是使用自己专属名字的 namespace

<?php

namespace MyProject;

function
my_function() {
return
true;
}

\MyProject\my_function();

这仍然需要你跟踪已经使用过的命名空间,但一旦你用了在决定了要使用的命名空间后,你可以添加所有的函数和类到它,不用再考虑冲突。

最好的做法是,尽量控制一下添加到全局范围内的变量,以防止与第三方代码的命名产生命名空间冲突。

注意: 变量作用域

因为 PHP 的作用域规则,在函数和方法内定义的变量不会在全局作用域内,因此不会和全局作用域内其它定义的变量相冲突。

add a note add a note

User Contributed Notes 4 notes

up
27
willian at gt44 dot com
10 years ago
I don't think it makes sense nowadays. We have namespaces now!
up
1
kanone at rogers dot com
9 years ago
The javascript community has developed a strong cultural bias against adding anything to the global namespace.  (See e.g. Addy Osmani's article on Essential JavaScript Namespacing Patterns .)  Namespaces have been available in JS for many years and are ubiquitous.  There is also a great deal of freely available tutorial material for the interested reader.
up
1
mestresan AT gmail DOT com
9 years ago
Even though nowadays we do have namespaces, for the cases in which the user chooses to not use namespaces theses tips should be followed.
up
1
earnie at users dot sourceforge dot net
10 years ago
@willian at gt44 dot com: What about clashes of the namespace?  It is still good advice to check for previously used names before assigning anything to the global namespace.
To Top