note 118416 deleted from functions.returning-values by cmb

From: Date: Thu, 13 Aug 2020 09:31:44 +0000
Subject: note 118416 deleted from functions.returning-values by cmb
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-214953@lists.php.net to get a copy of this message
Note Submitter: Nathan Salter ---- 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

« previous php.notes (#214953) next »