I agree with SR, the new namespaces feature has solved a number of problems for me which would have required horrible coding to solve otherwise.
An example use:
Say you are making a small script, and write a class to connect to a database, calling it 'connection'. If you find your script useful and gradually expand it into a large application, you may want to rename the class. Without namespaces, you have to change the name and every reference to it (say in inheriting objects), possibly creating a load of bugs. With namespaces you can drop the related classes into a namespace with one line of code, and less chance of errors.
This is by no means one of the biggest problems namespaces solve; I would suggest reading about their advantages before citicising them. They provide an elegant solutions to several problems involved in creating complex systems.
名前空間の定義
名前空間の宣言は、namespace キーワードを用いて行います。これを、ファイルの先頭に記述しなければなりません。 たとえば次のようになります。
例1 名前空間の定義
<?php
namespace MyProject::DB;
const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */ }
?>
同一の名前空間を、複数のファイルで使用することもできます。
名前空間の中にはクラスや定数、関数定義を含めることができます。 ただしそれら以外のコードを含めることはできません。
名前空間の定義は次のようなものです。
- 名前空間の内部では、すべてのクラスや関数、 定数名には自動的に名前空間名のプレフィックスが付加されます。 クラス名は常にフルネームとなります。つまり、 上の例のクラスをコールする際は MyProject::DB::Connection とします。
- 定数を定義すると、名前空間名と定数名を組み合わせた定数を作成します。 クラス定数と同様、名前空間定数にも静的な値しか保持できません。
-
修飾されていないクラス名 (:: を含まない名前) は、実行時に次の手順で解決されます。
- そのクラスを、現在の名前空間から (つまり現在の名前空間名を先頭につけて) 探します。 その際には autoload を試みません。
- グローバル名前空間から、autoload を試みずにそのクラスを探します。
- 現在の名前空間で autoload を試みます。
- 以上がすべて失敗した場合は、クラスの検索が失敗します。
-
修飾されていない関数名 (:: を含まない名前) は、実行時にまず現在の名前空間で探され、 次にグローバル空間で探します。
-
修飾されていない定数名は、 まず現在の名前空間で探され、次にグローバル空間で探します。
完全な 名前解決の規則 も参照ください。
名前空間の定義
David Drakard
07-Sep-2008 05:56
07-Sep-2008 05:56
Baptiste
14-May-2008 12:47
14-May-2008 12:47
There is nothing wrong with PHP namespaces, except that those 2 instructions give a false impression of package management.
... while they just correspond to the "with()" instruction of Javascript.
By contrast, a package is a namespace for its members, but it offers more (like deployment facilities), and a compiler knows exactly what classes are in a package, and where to find them.
Anonymous
01-Apr-2008 12:11
01-Apr-2008 12:11
@ RS: Also, you can specify how your __autoload() function looks for the files. That way another users namespace classes cannot overwrite yours unless they replace your file specifically.
