2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

namespaceの使い方

Last updated at Posted at 2017-07-05

名前空間

名前空間は下記の様に定義させる。基本的に名前空間の宣言より前にはコメント以外の出力や文が存在してはいけない。

namespace 名前空間;

また、名前空間を機能によって階層化させる場合、バックスラッシュ()で区切る

namespace 名前空間\サブ名前空間; (例:namespace Project\Module)

lib1_2.php

//1つのファイルに複数の名前空間の定義をすることも可能
<?php 
namespace Lib1;
class Foo {
    public function get_foo() {
        return 'lib1.foo';
    }
}

//ここから Lib2の名前空間の中
namespace Lib2;
class Foo {
    public function get_foo() {
        return 'lib2.foo';
    }
}
?>
lib3.php
<?php 
    namespace Lib3;
    class Foo {
    	public function get_foo() {
             return 'lib3.foo';
    	}
    }
?>
class.php
<?php 
	// namespaceの使い方
	require_once 'lib1_2.php';
	require_once 'lib3.php';

	$foo = new Lib1\Foo();
	echo $foo -> get_foo();//lib1.foo

	$foo = new Lib2\Foo();
	echo $foo -> get_foo();

	$foo = new Lib3\Foo();
	echo $foo -> get_foo();//lib3.foo
?>

インポートツール

名前空間を使う際、別の名前空間やそれに属するクラスをuseキーワードを使ってインポートしたり、asキーワードにより別名をつけることができます。定数と関数はこれによってインポートすることはできない

qiita.php
use \クラス名;
use 名前空間;
use 名前空間 as 別名;
use 名前空間 \クラス名;

たとえば、次のように記述することにより、Project\Moudule2名前空間をAnotherMouduleという別名で扱うことができるようになる

example.php
namespace Project\Moudule;
use Project\Moudule2 as AnotherMoudule;

$obj = new AnotherModule\SomeClass(); //new Project\Moudule2\SomeClass() と同様
2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?