CakeFest 2024: The Official CakePHP Conference

名前空間の使用法: グローバル関数/定数への移行

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

名前空間内で、PHP が未定義のクラス名や関数、定数に出会った場合、 それぞれに応じて異なる優先順位で解決を行います。 クラス名は、常に現在の名前空間での名前として解釈されます。 したがって、内部クラスあるいは名前空間に属さないクラスにアクセスするには 次のように完全修飾名で指定しなければなりません。

例1 名前空間内からのグローバルクラスへのアクセス

<?php
namespace A\B\C;
class
Exception extends \Exception {}

$a = new Exception('hi'); // $a は A\B\C\Exception クラスのオブジェクトです
$b = new \Exception('hi'); // $b は Exception クラスのオブジェクトです

$c = new ArrayObject; // fatal error, class A\B\C\ArrayObject not found
?>

関数や定数の場合、名前空間内にその関数や定数が見つからなければ PHP はグローバル関数/定数を探します。

例2 名前空間内からのグローバル関数/定数への移行

<?php
namespace A\B\C;

const
E_ERROR = 45;
function
strlen($str)
{
return
\strlen($str) - 1;
}

echo
E_ERROR, "\n"; // "45" と表示します
echo INI_ALL, "\n"; // "7" と表示します - グローバルの INI_ALL に移行しました

echo strlen('hi'), "\n"; // "1" と表示します
if (is_array('hi')) { // "is not array" と表示します
echo "is array\n";
} else {
echo
"is not array\n";
}
?>

add a note

User Contributed Notes 1 note

up
35
markus at malkusch dot de
9 years ago
You can use the fallback policy to provide mocks for built-in functions like time(). You therefore have to call those functions unqualified:

<?php
namespace foo;

function
time() {
return
1234;
}

assert (1234 == time());
?>

However there's a restriction that you have to define the mock function before the first usage in the tested class method. This is documented in Bug #68541.

You can find the mock library php-mock at GitHub.
To Top