我有一个包含以下部分的脚本:
function checkDays($oldDate){
// calculate time
// Print table row style based on number of days passed
// (eg less than 1 week, 1 week, 2 weeks, 3weeks+)
}
//Some code
checkdays($value)
我想放置一个计数器,记录每个时间段有多少条记录,函数本身在循环内,因此它为表的每一行调用,而且我似乎无法访问函数本身之外定义的变量所以我可以改变它们(例如,在脚本顶部放置一个计数器并从函数中修改它)。
有人说使用全局变量,但我知道这是一种风险,不推荐。有没有一种简单的方法可以从函数中访问变量?另外,有没有更好的方法来完成我在这里所做的一切?
最佳答案
不要试图使用全局变量
您可以通过引用传递变量,这意味着传递的是实际变量而不是它的副本:
$count = 0;
//Some code
checkdays($value, $count);
checkdays($value, $count);
checkdays($value, $count);
// This will output 3
echo $count;
// Use a & to pass by reference
function checkDays($oldDate, &$count){
// Your code goes here as normal
// Increment $count, because it was passed by reference the
// actual variable was passed
// into the function rather than a copy of the variable
$count++;
}
关于php - 如何在 PHP 中修改函数外部的变量/更好的做某事的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4889057/