如果执行 sort(&$myArray) 有问题吗?
PHP 手册说你必须执行sort($array)
。 $array
将通过引用传递,因此 sort()
将修改 $myArray
。
我只是想知道如果您执行 sort(&$myArray)
是否有任何问题或暗示。
PHP manual says you have to do sort($array)
. $array
will be passed by reference, so sort()
will modify $myArray
.
I'm just wondering if there is any problem or implication if you do sort(&$myArray)
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
给出更详细的答案:
反对传递引用的原因是分散的。主要是代码清洁度。其次,它经常被新手滥用,如果无人监督,会导致副作用。 (如果新手误用曾经是弃用的一个充分理由,那么
mysql_query
应该早就消失了。)第三,当 ZendVM 不期望时,通过引用传递参数实际上存在一些内部内存管理问题。 (Quercus 和 Project Zero 不存在此类问题。)
To give a more detailed answer:
The reasoning for deprecating pass-by-references is diffuse. It's mostly code-cleanliness. Secondly it was commonly misused by newcomers, leading to side-effects if unsupervised. (If newcomer misuse ever was a good reason for deprecation, then
mysql_query
should have been long gone.)And thirdly, there are in fact some internal memory management issues with passing parameters by reference when the ZendVM does not expect it. (Quercus and Project Zero do not have such issues.)
简短的回答是,这不会有什么不同。
长的答案是你应该不惜一切代价避免引用。它们是错误的主要来源,而且您确实不需要它们。需要参考文献来解决问题的情况很少见,但这种情况很少而且间隔很远。
之所以有很多引用,是因为在 PHP 5.0 之前,没有对象引用的概念。因此,您需要通过引用传递所有对象(并通过引用返回它们)以获得任何类型的 OO 功能(允许方法修改对象等)。但从 5.0 开始(已有十年历史),就不再需要了。要了解它现在的工作原理,我建议阅读
因此,请进行更可维护和正确的用法:
The short answer is it won't make a difference.
The long answer is that you should avoid references at all cost. They are a major source of bugs, and you really don't need them. There are a few rare occurrences where references are needed to solve a problem, but they are very few and very far between.
The reason there are a lot of references, is prior to PHP 5.0, there was no concept of object references. So you needed to pass all objects by reference (and return them by reference) to get any kind of OO functionality (allow methods to modify the object, etc). But since 5.0 (which is a decade old), that's no longer needed. To understand how it works now, I'd suggest reading this answer.
So do the more maintainable and correct usage: