很多时候,当我有一个小的配置文件,如 Doctrine cli-config.php 文件时,我需要使用一些临时变量,当这个文件包含在其他地方时,我不想作为全局变量泄漏。
例如,在以下配置文件中,$container
和$em
包含它的代码上下文中泄漏:
$container = Bootstrap::createDependencyInjectionContainer();
$em = $container->get('Doctrine'ORM'EntityManager');
return new 'Symfony'Component'Console'Helper'HelperSet(array(
'db' => new Helper'ConnectionHelper($em->getConnection()),
'em' => new Helper'EntityManagerHelper($em)
));
在 Javascript 中,我可以使用以下构造来隔离代码块:
(function() {
})();
但是在 PHP 中,即使匿名函数确实存在,上面的结构也不起作用:
解析错误:语法错误,意外的"("...
因此,我可以看到保护我的临时变量不被全局化的唯一方法是将代码包装在命名函数中:
function create_my_config() {
// wrap the cli-config.php code above
}
return create_my_config();
但这现在泄漏了一个全局函数名称。当然,我可以将其命名为命名空间,但我不确定这是否更好。
有没有办法在不创建命名函数的情况下隔离代码块及其所有变量?
PHP 不支持自调用匿名函数,但你仍然可以用call_user_func
索引.php:
<?php
$config = require 'config.php';
配置.php:
<?php
return call_user_func(function(){
return ["host" => "localhost", "user" => "root", "password" => ""];
});