我可以从函数到外部范围定义变量吗?

时间:2014-12-08 08:23:49

标签: php

在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不允许我这样做?有没有其他方法来完成任务? (减少函数中的重复定义并再次定义外部)

2 个答案:

答案 0 :(得分:2)

如果函数返回一个数组。它有理由这样做。函数应仅使用给定的函数,并在需要时返回结果。它永远不应该设置任何全局变量(除非该函数被称为setGlobalVariable,那么它有一个原因)。

如果要将返回的数组映射到变量。使用list

list($a,$b,$c) = getSomeData();

答案 1 :(得分:-1)

试试这个...

$data_A = '';
$data_B = '';
$data_C = '';

function getSomeData(){
 //this function will set variable at the upper level scope
 global $data_A, $data_B, $data_C; //Using global

 $data_A = 'foo';
 $data_B = 'bar';
 $data_C = 42;

 return true;
}

//1. we call the function
getSomeData(); 

//2. Then we use it right here
doSomething($data_A);
doSomethingElse($data_B); 
相关问题