混淆理解 PHP 命名空间



我正在学习和实现PHP命名空间。 请参考以下代码:

<?php
namespace Xicorcore;
class App {
public function __construct() {
$registry = Registry::getInstance();
//TODO: init router
//TODO: call controller@action
$controllerName = 'Xicorappcontrollers\'.'Index';
$action = 'show';
$controller = new $controllerName();
$controller->$action();
}
}

上面的代码完美运行。

如果我在构造函数中添加throw new Exception('Lorem Ipsum'),我会按预期收到错误。为了使它工作,我必须使用throw new Exception('Lorem Ipsum')以便我们引用全局命名空间。

但是,为什么$controllerName = 'Xicorappcontrollers\'.'Index';成功导入正确的类。

为什么我不必使用$controllerName = 'Xicorappcontrollers\'.'Index';(带\前缀(?

如果它影响任何东西,这是我的自动加载机:

<?php
spl_autoload_register(function($name) {
//replace  with DIRECTORY_SEPARATOR
$path = str_replace('\', DS, $name);
//replace Xicor with root
$path = str_replace('Xicor', __DIR__, $path); // __DIR__ doesn't return a trailing slash
//add .php at end
$path .= '.php';
if(file_exists($path)) {
require_once($path);
}
});

据我了解。PHP 将在类的当前命名空间中工作,除非另有指定(前面的 \(。

namespace Bar;
class Foo {
function __construct()
{
// references current namespace, looks for BarBaz;
$baz = new Baz();
}
}
class Baz {
function __construct()
{
try {
// do stuff
// references global namespace
} catch(Exception $e) {
var_dump($e->getMessage());
}

}
function foo() {
// This will prepend the current namespace to the class, in actual fact it will first look for "BarBarFoo"
// When it isnt found, it will move on and look at spl_autoload_register to try to resolve this class,
// Failing that you will get a ClassNotFoundException
$foo = new BarFoo();
}
}

请看,https://www.php.net/manual/en/language.namespaces.rules.php 和 https://www.php.net/manual/en/language.namespaces.faq.php#language.namespaces.faq.full 供参考

最新更新