|
php.net | support | documentation | report a bug | advanced search | search howto | statistics | random bug | login |
[2013-02-21 14:22 UTC] stormbyte at gmail dot com
Description:
------------
One of major benefits from PHP is that it is very close to C/C++ style, so it is its functions and coding style (very similar for, while and those constructs) so if you come from C/C++ world, you have it easy.
To keep this consistence I suggest, as well as C/C++ does, passing arrays as reference in function arguments by default, or at least an option to behave like that.
For me, it does not make much sense to "follow" C/C++ coding styles and behaviour, while not following that behaviour.
Furthermore, objects are already passed by reference as default, so why not arrays? IMHO I think that inconsistence may confuse programmers.
Test script:
---------------
function foo($arr) {
array_push($arr, "test");
}
function bar(&$arr) {
array_push($arr, "test");
}
$a=array();
foo($a);
//$a is empty
bar($a);
//$a[0]="test"
Expected result:
----------------
To be consistent with the rest behaviour of "imitating" C/C++ and pass arrays as reference automatically as well as objects are.
Also, it may be a performance gain by doing that (which is one of the reasons in C world it is that way)
PatchesPull RequestsHistoryAllCommentsChangesGit/SVN commits
|
|||||||||||||||||||||||||||||||||
Copyright © 2001-2025 The PHP GroupAll rights reserved. |
Last updated: Wed Dec 03 12:00:01 2025 UTC |
@stormbyte >objects are already passed by reference as default Nope. Objects in PHP 5+ are not like those in C (which are value-types); PHP objects have implicit reference semantics (same as Java). But parameters are ALWAYS passed by value unless the '&' is there explicitly. Example: class Foo { public $i; public function __construct($i) { $this->i = $i; } public function __toString() { return $this->i . ''; } } $obj1 = new Foo(1); $obj2 = new Foo(2); $obj = $obj1; echo $obj; doSomethingWith($obj); function doSomethingWith($obj) { $obj->i = 3; $obj = $GLOBALS['obj2']; echo $obj; } echo $obj; echo $obj1; --------------------- Output is 1233. If PHP passed objects by reference by default, it would be 1223, which is the same value you'll get if you manually add the '&' to the parameter declaration. However, notice obj1 gets modified either way (the last digit) because even the plain assignment ($obj = $obj1) assigns the object address and not the contents.