在PHP中,我总是看到例如从函数得到的数据是这样的:我可以定义从函数到外部范围的变量吗?
function getSomeData(){
//this function will return a array of data
$data_A = 'foo';
$data_B = 'bar';
$data_C = 42;
return array('data_A'=>$data_A, 'data_B'=>$data_B, 'data_C'=>$data_C,)
}
//1. we call the function
$models = getSomeData();
//2. Now we need to define the variable by the return value.
$data_A = $models['data_A'];
$data_B = $models['data_B'];
$data_C = $models['data_C'];
//3. Then we can do whatever with those defined variable
doSomething($data_A);
doSomethingElse($data_B);
这看起来平常。现在,这个怎么样:
function getSomeData(){
$data_A = 'foo';
$data_B = 'bar';
$data_C = 42;
someMagicFunction($data_A); //this function will set variable at the upper level scope
someMagicFunction($data_B);
someMagicFunction($data_C);
return true;
}
//1. we call the function
getSomeData();
//2. Then we use it right here
doSomething($data_A);
doSomethingElse($data_B);
我想是尝试跳过第2步,我将需要能够“在上级范围设置变量”的功能。 有时候我觉得第2步有点“不必要” - 我认为没有那些代码可以简单而干净。
假设代码是在一个类或匿名函数中,而不是在根级别中,是否有可能?如果没有,为什么PHP不允许我这样做?有没有其他的方法来完成这项任务? (减少函数中的重复定义并再次定义外部)
这是一个坏主意,要做到这一点,因为作用域是机制来保护你的变量。但是,您可以使用全局变量来执行此操作; http://php.net/manual/en/reserved.variables.globals.php – RichardBernards 2014-12-08 08:25:16
“假设代码位于类或匿名函数中,而不是根级” – LunaCat 2014-12-08 08:25:46
呃...使用类变量和'$ this' ?我可能不是很了解你的问题......请给出一个确切的例子,说明你想如何工作... – RichardBernards 2014-12-08 08:27:36