PHP Velho Oeste 2024

Tips

将来もそのまま使用できるようなコードを書くためには、 グローバル名前空間にあまり多くの変数や関数やクラスを置かないことをおすすめします。 そうしておけば、サードパーティのコードと名前が衝突したり PHP 自体に追加された機能と名前が衝突したりする可能性を減らせます。

関数やクラスの名前が衝突することを防ぐ手としてよくあるのが、 それ専用の 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