LoginSignup
0
0

More than 5 years have passed since last update.

名前空間の小さなサンプルメモ

Posted at

これはもちろんエラー

namespace1.php
<?php

function test(){
        echo "test";
}

function test(){
        echo "test";
}
  • 1つのファイル内で名前空間を複数宣言
    • 宣言以下が当該名前空間になる
  • 名前空間の使用は「XXX\YYY」のように記載すると、現在の名前空間からの相対パスのような形で参照される
  • 「\XXX\YYY」のように記載すると、絶対パスのように参照される
namespace2.php
<?php

namespace kuredev1;
echo  __NAMESPACE__."\n";
function test(){
        echo "test1\n";
}

namespace kuredev2;
echo  __NAMESPACE__."\n";
function test(){
        echo "test2\n";
}

test();//kuredev2\test()
//kuredev2\test();// kuredev2\kuredev2\test()
//kuredev1\test();  // kuredev2\kuredev1\test()
\kuredev1\test();
\kuredev2\test();
実行結果
# php namespace3.php
kuredev1
kuredev2
test2
test1
test2
teset
  • requireしても名前空間はそのファイル内で宣言しないとその名前空間にならない
namespace3.php
<?php

require_once "namespace2.php";

echo "test\n";
echo __NAMESPACE__."\n";
実行結果
# php namespace3.php
kuredev1
kuredev2
test2
test1
test2
test

0
0
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
0
0