我试图在每次调用函数时都这样做,它应该返回两倍于这样的数字:
calls(); // NULL
calls(); // 2
calls(); // NULL
calls(); // 4
这是我的代码:
function calls() {
if (NULL) {
return NULL;
}
else {
$calls++;
return $calls;
}
}
calls(); // NULL
calls(); // 2
calls(); // NULL
calls(); // 4
答案 0 :(得分:1)
不要使用全局变量,在相关函数中使用static
变量:
function count_calls() {
static $count = 0;
++$count;
return ($count % 2 === 0) ? $count : NULL ;
}
答案 1 :(得分:0)
以下是您应该做的例子:
$current = 0;
$current = calls($current); // NULL
echo display($current);
$current = calls($current); // 2
echo display($current);
$current = calls($current); // NULL
echo display($current);
$current = calls($current); // 4
echo display($current);
/**
* Do stuff for your call with in param your last call pointer and returns new pointer
**/
function calls($last) {
return $last++;
}
/**
* Returns null if not even, else the pointer value
**/
function display($value){
if ($value % 2 = 0)
return $value;
return null;
}
当然,如果你将当前指针存储在$ this->当前内容中,对象会更容易,但是我不认为你所显示的代码在适当的时候被你的理解所占用!好好玩吧
$class = new Call();
$class->calls();
echo $class->display();
$class->calls();
echo $class->display();
$class->calls();
echo $class->display();
$class->calls();
echo $class->display();
class Call {
private $current = 0;
/**
* Do stuff for your call with in param your last call pointer and returns new pointer
**/
function calls() {
$this->current++:
return $this->current;
}
/**
* Returns null if not even, else the pointer value
**/
function display(){
if ($this->current % 2 = 0)
return $this->current;
return null;
}
}
答案 2 :(得分:0)
检查此代码:
$calls = 0;
function calls() {
$GLOBALS['calls']++;
if ($GLOBALS['calls'] % 2 != 0) {
return NULL;
}
else {
//$GLOBALS['calls']++;
return $GLOBALS['calls'];
}
}
var_dump(calls()); // NULL
var_dump(calls()); // 2
var_dump(calls()); // NULL
var_dump(calls()); // 4