note 122018 added to language.variables.scope
| From: | jordan at brownboots dot com | Date: | Wed, 13 Dec 2017 22:59:12 +0000 |
| Subject: | note 122018 added to language.variables.scope | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-209363@lists.php.net to get a copy of this message | ||
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
?>
----
Server IP: 208.43.231.9
Probable Submitter: 68.190.81.78
----
Manual Page -- http://php.net/manual/en/language.variables.scope.php
Edit -- https://master.php.net/note/edit/122018
Del: integrated -- https://master.php.net/note/delete/122018/integrated
Del: useless -- https://master.php.net/note/delete/122018/useless
Del: bad code -- https://master.php.net/note/delete/122018/bad+code
Del: spam -- https://master.php.net/note/delete/122018/spam
Del: non-english -- https://master.php.net/note/delete/122018/non-english
Del: in docs -- https://master.php.net/note/delete/122018/in+docs
Del: other reasons-- https://master.php.net/note/delete/122018
Reject -- https://master.php.net/note/reject/122018
Search -- https://master.php.net/manage/user-notes.php