【发布时间】:2015-09-12 10:17:49
【问题描述】:
在某些命名空间中,定义了一个具有静态方法的类。为了使名称更短,我为此方法使用速记别名。别名在全局命名空间中定义。 自动加载出现问题。在加载类之前不能使用别名。
示例。 假设如下结构
composer.json
index.php
src/
Utils/
Dumper.php
文件src/Utils/Dumper.php 定义类MyVendor\Utils\Dumper 并在全局命名空间中定义别名_d()
<?php
namespace MyVendor\Utils {
class Dumper
{
public static function show($x)
{
echo "<pre>" . print_r($x, true) . "</pre>";
}
}
}
namespace {
if ( !function_exists( '_d' ) ) {
function _d()
{
$_ = func_get_args();
return call_user_func_array(
array( 'MyVendor\Utils\Dumper', 'show' ),
$_
);
}
}
}
?>
文件 composer.json 创建 PSR-4 自动加载器。
{
"autoload": {
"psr-4": {
"MyVendor\\": "src/"
}
}
}
我不能使用别名_d(),因为不需要类Dumper。
代码
<!DOCTYPE html>
<html lang="en">
<head> <meta charset='utf-8'> </head>
<body>
<?php
require_once 'vendor/autoload.php';
use MyVendor\Utils\Dumper;
$arr = array(10, 20, 30);
//Dumper::show($arr);
_d($arr);
?>
</body>
</html>
导致Fatal error: Call to undefined function _d() in index.php on line 13
有一个明显的解决方案。一旦使用了Dumper,它就必须被自动加载,所以整个src/Utils/Dumper.php 都被包含在内,并且还生成了别名。
Dumper::show($arr);
_d($arr);
但这不是我的意思。
每当我将我的Utils 包移动到另一个项目时,我都必须记住第一次使用Dumper::show()。
任何其他用户也必须意识到这个障碍。
有没有更好的解决方案?
【问题讨论】:
标签: php namespaces