php-每次调用函数时返回两次
我试图使它在每次调用函数时,都会返回1/2的数字,如下所示:php-每次调用函数时返回两次,php,Php,我试图使它在每次调用函数时,都会返回1/2的数字,如下所示: calls(); // NULL calls(); // 2 calls(); // NULL calls(); // 4 这是我的密码: function calls() { if (NULL) { return NULL; } else { $calls++; return $calls; } } calls(); // NULL calls()
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
以下是您应该做的示例:
$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->current中,在object中会更容易,但我不认为您显示的代码适合您目前的理解!已经玩得很开心了
$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;
}
}
检查此代码:
$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
不要使用全局变量,在相关函数中使用
静态
变量:
function count_calls() {
static $count = 0;
++$count;
return ($count % 2 === 0) ? $count : NULL ;
}
带有
变量和%模的东西<代码>%$var/2==0
。使用静态变量并在偶数时返回值。函数通常没有任何持久状态。您需要一个类或闭包来保持函数调用之间的状态。抱歉,我必须在不使用对象中的任何参数的情况下执行此操作,请注意,如果您愿意,可以合并我的两个函数,我只是将其分开,因为这样更容易理解。我刚刚更新了echo以返回值,请注意,在我的示例中,返回current in calls函数这一事实现在已经过时,但根据您在类之外所做的工作,它可能对您有用。