views:

21

answers:

3

Consider the functions sort and array_reverse.

Why does one modify the variable passed, whereas the other return a new version?

$a = array(3, 1, 2);

sort($a);
// $a === array(1, 2, 3)

array_reverse($a);
// $a === array(1, 2, 3)

sort could just as easily been written to return a modified copy of the argument, and vice-versa for array_reverse.

The reason I'm asking is because I want to know if there's any guidelines for deciding whether write functions using the "pass-by-reference and modify" approach vs the "pass-by-value, modify and return" approach.

+1  A: 

One of PHP's annoyances is that the API is really inconsistent. For example:

  • Inconsistent parameter ordering (needle, haystack);
  • Inconsistent use of underscores. Some functions even use an underscore in one part but not in another.

I think the pass-by-reference vs copy thing is largely in the same boat.

cletus
yeah PHP methods are all over the shop, but do you have any recommendations for writing your own functions?
nickf
+1  A: 

I think that user intent is probably the most important thing here. Not that it is very obvious in the particular example that you chose, but in general I'd guess that I'd want to think about what a user would expect (destructive in-place modification vs newly constructed return values) when designing an API.

danben
A: 

I'd recommend sticking to pass-by-value, return copy as it's a safer assumption. Pass-by-reference, args modified only make sense where there are 2 distinct operations happening, e.g. shift, where the array is modified but the first element returned

K Prime