开发者

Is there any problem if you do sort(&$myArray)?

开发者 https://www.devze.com 2023-04-01 03:44 出处:网络
PHP manu开发者_开发问答al says you have to do sort($array). $array will be passed by reference, so sort() will modify $myArray.

PHP manu开发者_开发问答al 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).


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


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);
0

精彩评论

暂无评论...
验证码 换一张
取 消