Reputation: 546095
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.
Upvotes: 2
Views: 54
Reputation: 5849
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 return
ed
Upvotes: 0
Reputation: 83250
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.
Upvotes: 1
Reputation: 625147
One of PHP's annoyances is that the API is really inconsistent. For example:
I think the pass-by-reference vs copy thing is largely in the same boat.
Upvotes: 1