sorry about the funky title, I was having trouble coming up with one. First off, I managed to actually solve my problem (after tearing apart my code), but I have no idea WHY my solution worked and I am trying to treat this as a learning experience.
I have a class which collects info from the db. This class tracks an index value so that the calling function can grab the results one at a time. So my class code originally contained...
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];
}
And the calling function has something akin to
while($myclass->next_item()){
echo $myclass->get_result();
}
It's all a lot more involved than this of course, but this is the problem code (and you get the idea). This code induced an infinite loop (or the appearance of one) in my project. I fixed my problem by initializing $index to -1, and removing the conditional check for null. So it's now ...
protected $index = -1;
public function next_item()
{
$this->index++;
if($this->index < sizeof($this->array))
{
return TRUE;
}
return FALSE;
}
My question is, WHY did that work? The index was never referenced in the array while it was NULL, I checked. It was always after the conditional check for NULL was called and the assignment to 0 occurred.
I really appreciate your time, in advance. Just trying to turn this into a learning experience, and it's better if I understand why it worked, not just that it did.
I'm sorry if this question is answered somewhere else, I couldn't figure out how to label my question (as you can see) much less have success finding a previous answer to it.
cheers, -David