Zend Studio reports warning: Assignment in conditi

2019-01-19 14:09发布

I have recently started using Zend Studio which has reported as warning the following type of code:

$q = query("select * from some_table where some_condition");
while ($f = fetch($q)) {
  // some inner workings
}

To stop the warning the code needs to be written like this:

$q = query("select * from some_table where some_condition");
$f = fetch($q);
while ($f) {
  // some inner workings
  $f = fetch($q);
}

Why is this marked as a warning? Is it so bad?

I understand that the warning may be designed to stop errors like this:

$a = 1;
while ($a = 1) {
  // some inner workings
  $a++;
}

which will never terminate because 1 is being assigned to $a which in turn returns 1 to the while statement, rather than being tested against $a and returning false to the while statement when $a is not 1.

Easy error to make which may validate a warning, granted, but so is forgetting to add the extra $f = fetch($q) at the end of the while block in the second example which will also result in a loop that will never terminate. If I change my code to remove the warning and then forget to add the $f = fetch($q) at the end of the while block Zend won't warning be about that!

So by removing the warning concerning a common error I'm setting myself up for a different common error.

Out of the pan, into the fire.

8条回答
欢心
2楼-- · 2019-01-19 14:58

So you won't have to rewrite all your code without a decent reason: You can disable the detection of this potential programming error in Window | Preferences, PHP | Semantic Analysis.

查看更多
SAY GOODBYE
3楼-- · 2019-01-19 15:04

Actually, I guess your question has already been answered, somewhat. But to address your actual problem, I think this might help.

//i dont know what is returned if there are no more records to fetch...
//but lets assume it is a boolean value
while (($f = fetch($q))!= false)
{
    $this->doSomethingVeryImportantThatMakesYourBossHappy($f);
}

That should do the trick and the "Assignment in condition"-message should disappear.

As a sidenote: use the equals operator the same way as when you negate stuff. You also use the equals sign with other operators like

if ($falseness != false){$trueness = true}

and not

if ($falseness ! false){$trueness = false}

That helps me to always remember how to compare values and not assign values to them.

查看更多
登录 后发表回答