抱歉这个时髦的标题,我很难想出一个。首先,我设法真正解决了我的问题(在拆开我的代码之后),但我不知道为什么我的解决方案有效,我试图将其视为一种学习体验。
我有一个从数据库收集信息的类。此类跟踪索引值,以便调用函数一次获取一个结果。所以我的课程代码最初包含......
protected $index = NULL;
protected $array = array(stuff);
public function next_item()
{
if($this->index == NULL)
{//first time called
$this->index = 0;
}
else
{
$this->index++;
}
if($this->index < sizeof($this->array))
{
return TRUE;
}
return FALSE;
}
public function get_result()
{
return $this->array[$this->index];
}
调用函数类似于
while($myclass->next_item()){
echo $myclass->get_result();
}
当然,这比这要复杂得多,但这是问题代码(你明白了)。这段代码在我的项目中引发了一个无限循环(或出现一个)。我通过将 $index 初始化为 -1 并删除对 null 的条件检查来解决我的问题。所以现在...
protected $index = -1;
public function next_item()
{
$this->index++;
if($this->index < sizeof($this->array))
{
return TRUE;
}
return FALSE;
}
我的问题是,为什么这样做有效?我检查过,当它为 NULL 时,数组中从未引用过该索引。它总是在调用 NULL 的条件检查并分配给 0 之后发生。
我真的很感谢你的时间,提前。只是想把它变成一种学习体验,如果我能理解它为什么起作用,而不仅仅是它起作用,那就更好了。
很抱歉,如果这个问题在其他地方得到了回答,我不知道如何标记我的问题(如您所见),更不用说成功找到以前的答案了。
干杯,-大卫