as noted by guilhermeblanco at php dot net,
<?php
// fact.php
namespace foo;
class fact {
public function create($class) {
return new $class();
}
}
?>
<?php
// bar.php
namespace foo;
class bar {
...
}
?>
<?php
// index.php
namespace foo;
include('fact.php');
$foofact = new fact();
$bar = $foofact->create('bar'); // attempts to create \bar
// even though foofact and
// bar reside in \foo
?>
名前空間と動的言語機能
PHP における名前空間の実装は、PHP 自身が動的プログラミング言語であるという性質に影響を受けています。 したがって、次の例のようなコードを名前空間を使って書き直すには
例1 要素への動的なアクセス
example1.php:
<?php
class classname
{
function __construct()
{
echo __METHOD__,"\n";
}
}
function funcname()
{
echo __FUNCTION__,"\n";
}
const constname = "global";
$a = 'classname';
$obj = new $a; // classname::__construct と表示します
$b = 'funcname';
$b(); // funcname と表示します
echo constant('constname'), "\n"; // global と表示します
?>
完全修飾名 (クラス名に名前空間プレフィックスをつけたもの) を使う必要があります。 動的なクラス名、関数名あるいは定数名においては修飾名と完全修飾名に差はないので、 先頭のバックスラッシュはなくてもかまいません。
例2 名前空間つき要素への動的なアクセス
<?php
namespace namespacename;
class classname
{
function __construct()
{
echo __METHOD__,"\n";
}
}
function funcname()
{
echo __FUNCTION__,"\n";
}
const constname = "namespaced";
include 'example1.php';
$a = 'classname';
$obj = new $a; // classname::__construct と表示します
$b = 'funcname';
$b(); // funcname と表示します
echo constant('constname'), "\n"; // global と表示します
/* ダブルクォートを使う場合は "\\namespacename\\classname" としなければなりません */
$a = '\namespacename\classname';
$obj = new $a; // namespacename\classname::__construct と表示します
$a = 'namespacename\classname';
$obj = new $a; // これも namespacename\classname::__construct と表示します
$b = 'namespacename\funcname';
$b(); // namespacename\funcname と表示します
$b = '\namespacename\funcname';
$b(); // これも namespacename\funcname と表示します
echo constant('\namespacename\constname'), "\n"; // namespaced と表示します
echo constant('namespacename\constname'), "\n"; // これも namespaced と表示します
?>
文字列中の名前空間名のエスケープに関する注意 を読んでおくことを忘れないようにしましょう。
名前空間と動的言語機能
scott at intothewild dot ca
07-Aug-2009 10:33
07-Aug-2009 10:33
guilhermeblanco at php dot net
16-Jun-2009 07:04
16-Jun-2009 07:04
Please be aware of FQCN (Full Qualified Class Name) point.
Many people will have troubles with this:
<?php
// File1.php
namespace foo;
class Bar { ... }
function factory($class) {
return new $class;
}
// File2.php
$bar = foofactory('Bar'); // Will try to instantiate \Bar, not \foo\Bar
?>
To fix that, and also incorporate a 2 step namespace resolution, you can check for \ as first char of $class, and if not present, build manually the FQCN:
<?php
// File1.php
namespace foo;
function factory($class) {
if ($class[0] != '\\') {
echo '->';
$class = '\\' . __NAMESPACE__ . '\\' . $class;
}
return new $class();
}
// File2.php
$bar = foofactory('Bar'); // Will correctly instantiate \foo\Bar
$bar2 = foofactory('\anotherfoo\Bar'); // Wil correctly instantiate \anotherfoo\Bar
?>
