调用内部php函数中的变量以在外部函数中使用


calling variables from inner php function to use in outer function

当前我有以下代码

在我的"function.php"中是

function calcTime($database_name,$currentTime){
    global $startTime;
    global $endTime;
    ...calcutions
    return $startTime;
    return $endTime;
}//end calcTime()

在我的主"index.php"中,我有

include('/function.php');
$databaseName = foo;
$currentTime = 12.30;
function begin($database_name,$currentTime){
    ...some calculations
    calcTime($database_name,$currentTime); //calling the function from other file
echo $startTime;
echo $endTime;
}// end begin()

我遇到的问题是,在内部函数中声明的变量不会传递到外部函数。我已经声明了变量globals并返回它们。不知道发生了什么。

不过,如果我回显calcTime($database_name,$currentTime),会有一些有趣的事情;返回$startTime,但不返回$endTime。

请帮忙。我有一些函数在我想以这种方式使用的其他函数中使用。非常感谢。

PHP中的global关键字用于访问在函数外部声明的全局变量。它是写作$var =& $GLOBALS['var']的句法糖。

至少有两种选择可以从函数中返回两个变量:通过ref调用或返回数组:

function calcTime($database_name,$currentTime){
    return array('start' => $startTime, 'end' =>  $endTime);
}
$times = calcTime(…, …);
echo $times['start'], ' and ', $times['end'];
// or:
list($start, $end) = calcTime(…, …);
echo $start, ' and ', $end;

或者,将参数作为引用传递:

function calcTime($database_name,$currentTime, &$startTime, &$endTime){
    $startTime = …;
    $endTime = …;
}
$startTime = 0;
$endTime = 0;
calcTime(…, …, $startTime, $endTime);
echo $startTime, ' and ', $endTime;

第一个问题是PHP中的global有点违反直觉。我知道这让我很困惑。它没有让函数内部的变量可以在外部访问;相反,它允许您在函数中使用外部声明的变量,例如:

$foo = 'hello';
function bar() {
    global $foo;
    echo $foo;
}

您要做的是返回这两个变量。但是,您只能return一次。一旦PHP到达return语句,它就会结束该函数,因此第二个函数永远不会运行。

我建议返回一个包含两个值的数组,例如:

return array('startTime' => $startTime, 'endTime' => $endTime);

然后,您可以使用extract使它们再次变为变量:

extract( calcTime() );
echo $startTime;
echo $endTime;

简单地说:调用作用域也不是global作用域。。。因此,要使其工作,变量也必须声明global。请注意,(过度)使用全局变量被认为是一种糟糕的做法,对您的程序员同事(甚至在一段时间后)来说,这是一种地狱般的调试。偏好参数&退货。

**记住,当你在一个函数上设置一个全局或变量时,每个函数在php上都是孤立的,而这个函数只在函数范围上可见

当然,您只能返回一个值,但这可能是一个更复杂的值,如:

return array('startTime' => $startTime,'endTime' => $endTime);