Skip to content

Instantly share code, notes, and snippets.

@yano3nora
Created July 2, 2017 06:46
Show Gist options
  • Save yano3nora/aace052e49e408ff493431f5904154d0 to your computer and use it in GitHub Desktop.
Save yano3nora/aace052e49e408ff493431f5904154d0 to your computer and use it in GitHub Desktop.
[php: namespace] namespace note. #php

基本

  • 名前空間の宣言が namespace Hoge\Foo;
  • クラスをインポートが use Hoge\Foo\BarClass;
  • エイリアスは asuse Hoge\Foo\Bar as Piyo;
namespace Hoge\Foo;

class Bar {
  public function getName(){
    return __CLASS__;
  }
}

echo Bar::getName();  // Hoge\Foo\Bar

名前空間外のクラスをインポート

namespace Hoge\Foo;
use Zend\OAuth\Consumer;

$consumer = new Consumer();

クラス名の動的呼び出しは名前空間をフルパスにしないとダメ

// refs: http://note.onichannn.net/archives/2846
$className = 'Hoge';
new $className();  //error

$nameSpace = '\\Huga\\Piyo\\';
$className = $nameSpace.'Hoge';
new $className();  //ok

エイリアスを使った呼び出し

namespace Hoge\Foo;
use Zend\OAuth\Consumer as OAuthConsumer;

$consumer = new OAuthConsumer();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment