note 122018 deleted from language.variables.scope by cmb

From: Date: Sun, 27 Oct 2019 08:27:59 +0000
Subject: note 122018 deleted from language.variables.scope by cmb
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-212776@lists.php.net to get a copy of this message
Note Submitter: jordan at brownboots dot com ---- Using $GLOBALS inside a function you can override all references to global variables in that function with variables passed into the function as arguments. This is useful when a function does stuff to a global object but you sometimes want it to do that stuff to a different object, and you don't want to rewrite any code. For example, suppose there's a global object called $user that refers to the currently-logged-in user and a function that does stuff to that user object: <?php function example_function() { global $user; // do stuff with the object echo $user->id; } ?> Here's how you can make that function optionally do stuff to a different user object: <?php function example_function(&$user = null) { if(!isset($user)) { // if the function argument isn't provided, ... $user = $GLOBALS['user']; // ... use the global variable } // do stuff with the object echo $user->id; } ?> Example usage: <?php example_function(); // this will print the logged-in user's ID $test_user = load_user_by_id(1453); example_function($test_user); // this will print 1453 ?>

« previous php.notes (#212776) next »