note 118416 added to functions.returning-values

From: Date: Thu, 03 Dec 2015 09:17:50 +0000
Subject: note 118416 added to functions.returning-values
Groups: php.notes 
Request: Send a blank email to php-notes+get-204265@lists.php.net to get a copy of this message
Just a quick clarification on whether variables are passed by reference or not. Variables are always passed using a pointer, and if the variable is modified, it is copied and re-assigned. For example: <?php function byPointer($x) { return $x / 3; // Does not modify or create a copy of $x } function copied($x) { $x++; // At this point, creates a copy of $x to be used in local scope return $x; } class Obj { public function performAction() {} public $y; } function objPointer(Obj $x) { $x->performAction(); //works on $x $x->y = '150'; //works on $x $x = new Obj(); // Does not modify $x outside of function $x->y = '250'; } function objReference(Obj &$x) { $x->performAction(); //works on $x $x->y = '150'; //works on $x $x = new Obj(); // Modifies original $x outside of function $x->y = '250'; } $x = new Obj(); $x->y = '10'; objPointer($x); echo "Post Pointer: {$x->y}\n"; $x->y = '10'; objReference($x); echo "Post Reference: {$x->y}\n"; ?> This will output: Post Pointer: 150 Post Reference: 250 So make sure when writing functions that if you want to pass by reference you actually mean by reference, and not using standard PHP pointers ---- Server IP: 72.52.91.14 Probable Submitter: 188.92.232.164 ---- Manual Page -- http://php.net/manual/en/functions.returning-values.php Edit -- https://master.php.net/note/edit/118416 Del: integrated -- https://master.php.net/note/delete/118416/integrated Del: useless -- https://master.php.net/note/delete/118416/useless Del: bad code -- https://master.php.net/note/delete/118416/bad+code Del: spam -- https://master.php.net/note/delete/118416/spam Del: non-english -- https://master.php.net/note/delete/118416/non-english Del: in docs -- https://master.php.net/note/delete/118416/in+docs Del: other reasons-- https://master.php.net/note/delete/118416 Reject -- https://master.php.net/note/reject/118416 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#204265) next »