如果执行 sort(&$myArray) 有问题吗?

发布于 2024-12-02 13:18:02 字数 188 浏览 0 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

花海 2024-12-09 13:18:02

给出更详细的答案:

  • 它在 PHP 5.2 及之前版本中可以正常工作。
  • 它会在 PHP 5.3 上触发 E_DEPRECATED 警告(有时),
  • 并且很可能在 PHP 5.4 上停止工作。 (这在拒绝错误和内存违规错误之间交替。尚未最终确定,但这种更改可能会保留。)

反对传递引用的原因是分散的。主要是代码清洁度。其次,它经常被新手滥用,如果无人监督,会导致副作用。 (如果新手误用曾经是弃用的一个充分理由,那么 mysql_query 应该早就消失了。)
第三,当 ZendVM 不期望时,通过引用传递参数实际上存在一些内部内存管理问题。 (Quercus 和 Project Zero 不存在此类问题。)

To give a more detailed answer:

  • It'll work without issues in PHP 5.2 and before.
  • It'll trigger an E_DEPRECATED warning (sometimes) on PHP 5.3
  • It is very likely to stop working on PHP 5.4. (Which alternates between refusal and memory violation errors. Not finalized yet, but that change is likely to stay.)

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.)

夕嗳→ 2024-12-09 13:18:02

简短的回答是,这不会有什么不同。

长的答案是你应该不惜一切代价避免引用。它们是错误的主要来源,而且您确实不需要它们。需要参考文献来解决问题的情况很少见,但这种情况很少而且间隔很远。

之所以有很多引用,是因为在 PHP 5.0 之前,没有对象引用的概念。因此,您需要通过引用传递所有对象(并通过引用返回它们)以获得任何类型的 OO 功能(允许方法修改对象等)。但从 5.0 开始(已有十年历史),就不再需要了。要了解它现在的工作原理,我建议阅读

因此,请进行更可维护和正确的用法:

sort($myArray);

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:

sort($myArray);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文