在 PHP 中,当解析器遇到未限定的标识符(如类或函数名)时,默认会解析为当前命名空间。因此,为了访问 PHP 的预定义类,必须通过前缀 \
包含的文件会默认使用全局命名空间。因此,若要引用包含文件中的类,必须在类名前加上 \。
# test1.php
<?php
class myclass {
function hello() {
echo "Hello World";
}
}
?>
当此文件被包含到另一个 PHP 脚本中时,类需要通过 \ 来进行引用。
# test2.php
<?php
include 'test1.php';
class testclass extends \myclass {
function hello() {
echo "Hello PHP";
}
}
$obj1 = new \myclass();
$obj1->hello();
$obj2 = new testclass();
$obj2->hello();
?>
运行上述代码时,您将看到以下输出:
Hello World Hello PHP
通过以上示例,您可以清晰地了解如何在 PHP 中访问全局类以及如何在不同的命名空间中引用它们。