LoginSignup
19
15

More than 3 years have passed since last update.

PHPのnamespaceの使い方

Last updated at Posted at 2016-03-21

クラス名の重複

A.phpとB.phpがあり、これらのファイルにはそれぞれ、Humanクラスとrunメソッドが定義されているとする。

A.php
<?php
class Human{
  public function run(){
    return 'run';
  }
}
B.php
<?php
class Human{
  public function run(){
    return 'run';
  }
}

これら2つのファイルを読み込み、Humanクラスのインスタントを生成して、runメソッドを実行する。

<?php
require_once 'A.php';
require_once 'B.php';
$human = new Human();
echo $human->run().'\n';

以下のような、Fatal errorが発生する。
Fatal error: Cannot declare class Human, because the name is already in use in .../B.php on line 3

原因

  • A.php,B.phpで同じクラスを定義していて、名前が重複しているから。

エラー解決

  • A.php、B.phpにnamespace xxx;を追加
A.php
<?php
namespace A1; //これを追加した
class Human{
  public function run(){
    return 'a1 run';
  }
}
B.php
<?php
namespace B1; //これを追加した
class Human{
  public function run(){
    return 'b1 run';
  }
}

先ほど同様に、これら2つのファイルを読み込みHumanクラスのインスタントを生成して、runメソッドを実行する。

<?php
require_once 'A.php';
require_once 'B.php';
$human = new A1\Human();
echo $human->run().'\n'; //「a1 run」と出力

$human = new B1\Human();
echo $human->run().'\n'; //「b1 run」と出力 

A1というnamespace(名前空間)に属するHumanクラス、B1というnamespaceに属するHumanクラス、というようにそれぞれ区別できて、エラーは解決。

19
15
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
19
15