note 99660 added to functions.returning-values

From: Date: Sun, 29 Aug 2010 20:26:43 +0000
Subject: note 99660 added to functions.returning-values
Groups: php.notes 
Request: Send a blank email to php-notes+get-172149@lists.php.net to get a copy of this message
Developers with a C background may expect pass by reference semantics for arrays. It may be surprising that pass by value is used for arrays just like scalars. Objects are implicitly passed by reference. <?php # (1) Objects are always passed by reference and returned by reference class Obj { public $x; } function obj_inc_x($obj) { $obj->x++; return $obj; } $obj = new Obj(); $obj->x = 1; $obj2 = obj_inc_x($obj); obj_inc_x($obj2); print $obj->x . ', ' . $obj2->x . "\n"; # (2) Scalars are not passed by reference or returned as such function scalar_inc_x($x) { $x++; return $x; } $x = 1; $x2 = scalar_inc_x($x); scalar_inc_x($x2); print $x . ', ' . $x2 . "\n"; # (3) You have to force pass by reference and return by reference on scalars function &scalar_ref_inc_x(&$x) { $x++; return $x; } $x = 1; $x2 =& scalar_ref_inc_x($x); # Need reference here as well as the function sig scalar_ref_inc_x($x2); print $x . ', ' . $x2 . "\n"; # (4) Arrays use pass by value sematics just like scalars function array_inc_x($array) { $array{'x'}++; return $array; } $array = array(); $array['x'] = 1; $array2 = array_inc_x($array); array_inc_x($array2); print $array['x'] . ', ' . $array2['x'] . "\n"; # (5) You have to force pass by reference and return by reference on arrays function &array_ref_inc_x(&$array) { $array{'x'}++; return $array; } $array = array(); $array['x'] = 1; $array2 =& array_ref_inc_x($array); # Need reference here as well as the function sig array_ref_inc_x($array2); print $array['x'] . ', ' . $array2['x'] . "\n"; ---- Server IP: 69.147.83.197 Probable Submitter: 78.143.212.168 ---- Manual Page -- http://www.php.net/manual/en/functions.returning-values.php Edit -- https://master.php.net/note/edit/99660 Del: integrated -- https://master.php.net/note/delete/99660/integrated Del: useless -- https://master.php.net/note/delete/99660/useless Del: bad code -- https://master.php.net/note/delete/99660/bad+code Del: spam -- https://master.php.net/note/delete/99660/spam Del: non-english -- https://master.php.net/note/delete/99660/non-english Del: in docs -- https://master.php.net/note/delete/99660/in+docs Del: other reasons-- https://master.php.net/note/delete/99660 Reject -- https://master.php.net/note/reject/99660 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#172149) next »