错还是对? While 循环
嘿伙计们,现在我以前从来没有做过这个方法,我只是尝试了一下,看看它是否有效,它就像梦一样有效。
通常人们倾向于这样做。
$tags = array();
while($row = $statement->FetchObject())
{
$tags[] = $row;
}
但如果我这样做的话,会更快还是更少的代码。
$tags = array();
while($tags[] = $statement->FetchObject()){}
只是好奇,这就是全部
更新:
我确实知道更简洁的代码比更少的代码要好得多,但由于我之前从未使用过这种方法,所以这只是对利弊的好奇。
Heya guys, now ive never done this method before and i just tried it to see if it would work and it works like a dream.
Usually people tend to do this way.
$tags = array();
while($row = $statement->FetchObject())
{
$tags[] = $row;
}
but would it be faster or just less code if i done it this way.
$tags = array();
while($tags[] = $statement->FetchObject()){}
Just Curious that's all
Update:
I do understand that Cleaner code is much better then Less code, but as I never used this method before it was mere curiosity for pros and cons.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
一般问题是要退出
while
循环,需要返回“false”结果。在您的第二个示例中,这意味着数组末尾将有一个“false”值(这可能不是您想要的)。对于传统方法来说这不是问题,因为“false”值被赋予
$row
并且从未应用于数组。至于性能或可读性,它们不是问题,因为代码没有执行您希望它执行的操作。
The general issue is that to exit the
while
loop, a "false" result needs to be returned. In your second example, that means there will be a "false" value (which is likely not what you want) at the end of your array.This is not an issue for the traditional approach because the "false" value is given to
$row
and never applied to the array.As for performance, or readability, they're non-issues since the code doesn't do what you want it to do.
如果您的数据库类允许,只需使用预定义的方法即可实现此目的。例如,PDO 有
fetchAll
: <代码>$statement->fetchAll(PDO::FETCH_OBJ)。And if you're database class allows it, simply use the predefined method for this purpose. PDO for example has
fetchAll
:$statement->fetchAll(PDO::FETCH_OBJ)
.我发现前者更具可读性且易于掌握,并且我确信两者之间的任何性能差异都可以忽略不计。
我完全赞成1)。
I find the former much more readable and easy to grasp, and I'm sure any performance difference between the two is negligeable.
I'm all for 1).
您甚至可以跳过括号:
该代码肯定会更短一些,因为它的形式更冗长:
但是哪一个更容易阅读?你可以说两者都很明显,实际上我同意你的观点。但哪一种在一般维护上更容易呢?要以更短的形式添加像
$tag->doSth();
这样的新语句,您必须完全重写它。在最后一个中,您只需添加该语句即可。You could even skip the brackets:
That code certainly is a bit shorter that it's more verbose form:
However which one is easier to read? You could say both are quite obvious and actually I would agree with you. But which one is easier in general maintenance? To add a new statement like
$tag->doSth();
in shorter form you have to completely rewrite it. In the last one you just add that statement.当然,只要
FetchObject()
每次调用时都会适当地更改其返回值;)Sure, as long as
FetchObject()
changes its return value appropriately each time it's called ;)