“如果”与赋值是一个好的做法吗? [英] "If" with assignment is a good practice?
本文介绍了“如果”与赋值是一个好的做法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
请考虑这种情况:
大代码:
if($site->getUser($id)){
$user = $site->getUser($id);
//more code here
}
短代码:
if($user = $site->getUser($id)){
//already have the user
//more code here
}
在第一种情况下,我做2访问bbdd获取用户,但在第二个只有一个...
第二种情况,是一个好的做法?
in the first case, I do 2 access to bbdd for get the user, but in the second only one... the second case, is a good practice?
推荐答案
我更喜欢这个。
$user = $site->getUser($id);
if($user){
//more code here
}
一般来说,应避免条件下的赋值。许多编程语言甚至不允许它。太容易犯错误。
在可读性方面也更好。
Generally, assignments in conditions should be avoided. Many programming languages don't even allow it anymore. Too easy to make a mistake. It's also better in terms of readability.
这篇关于“如果”与赋值是一个好的做法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文