Man*_*023 2 php variables function
我有一个脚本,包含以下部分:
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)
Run Code Online (Sandbox Code Playgroud)
我想用一个计数器来计算每个时间段有多少条记录,函数本身就在一个循环内,所以它调用了表的每一行,而我似乎无法访问函数本身之外定义的变量所以我可以改变它们(例如,将一个计数器放在脚本的顶部并从函数中修改它).
有人说使用全局变量,但我知道这是一种风险,不推荐.有没有一种从函数中访问变量的简单方法?另外,有没有更好的方法来做我在这里做的总体事情?
我认为您所指的风险是register_globals,这完全是另一回事。
在函数内部,使用global关键字,例如
function myFunction($someParam) {
global $counter;
++$counter;
// do something
}
Run Code Online (Sandbox Code Playgroud)
或者,您可以执行所谓的 pass-by-reference 来修改传递给函数的外部作用域中的变量,例如
function myFunction($someParam, &$counter) {
++$counter;
// do something
}
Run Code Online (Sandbox Code Playgroud)
注意符号。
不要试图使用全局变量
您可以通过引用传递变量,这意味着传递实际变量而不是它的副本:
$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++;
}
Run Code Online (Sandbox Code Playgroud)