-3

我知道 while-condition 子句中的以下分配将起作用:

while ($info=mysql_fetch_array($data_jurisdiction))
{
//some stuff
}

$info被分配了一些值,while 条件将循环,除非分配的右侧返回 a FALSE, NULL, 0,array()等。

问题:在语言语法需要相等性检查的情况下进行分配是好还是坏?Zend Studio 立即指出这是一个警告。每种方法的优缺点是什么?

4

3 回答 3

0

它经常不受欢迎,因为它混淆了潜在的问题,并且有时除了你自己之外的开发人员更难阅读。那就是说我经常这样做,但是以分配和检查的方式进行,例如:

while(false !== ($info = mysql_fetch_array($result))) {

} 
于 2013-04-07T18:57:23.943 回答
0

问题的陈述是错误的。

There is no "Assignment Instead of Equality". An IF statement (as well as other control flow operators) is not limited to comparison operators only, but can evaluate almost any PHP expression. And language do not "expect an equality check" by any means. Language expects only a value that can be cast to boolean and compared to TRUE.
There is NO essential connection between IF operator and comparison operators. That's two distinct operators which can be used independently.

I.e. comparison without if:

$var = $a == $b; // $var now contains boolean value

and contrary:

if ($a + $b) // addition
if (isTrue()) // function
if ($var) // variable

every expression from the above will be evaluated, result cast to boolean and this boolean checked by IF statement.

So, it's all right as long as you understand what are you doing.

于 2013-04-07T18:59:00.867 回答
-1

您已经在问题中发现了问题所在。

该问题的解决方案通常是使用迭代器模式。

$jurisdictions = new MysqlResultIterator($data_jurisdiction);

foreach ($jurisdictions as $info)
{
    // some stuff
}

对于每个非mysql_*数据库库的支持,foreach都可以直接用于结果集。

Foreach 使无结果和下一个结果之间的区别更加明显。迭代器模式允许在不将其分配给结果变量的情况下表达有效性。

于 2013-04-07T18:56:53.507 回答