note 129208 added to language.variables.scope
| From: | randallfstewart at gmail dot com | Date: | Tue, 30 Jan 2024 20:25:46 +0000 |
| Subject: | note 129208 added to language.variables.scope | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-221162@lists.php.net to get a copy of this message | ||
Note that the global keyword inside a function does (at least) 2 different things:
1) As stated in the manual, it allows the function to use *the global version* of the variable:
"...all references to either variable will refer to *the global version*." [emphasis
mine]
2) As not stated in the manual, if the variable does not already exist in the global scope, it is
created in the global scope.
For example, in the code below, the variable $A is available in the global scope (after functionA is
called), even though it was never declared in the global scope:
<?php
echo "<p>This is A before functionA is called: {$A}.</p>";
functionA();
function functionA(){
global $A;
$A = "Declared as global inside functionA";
} // end fcn callGlobal
echo "<p>This is A after functionA is called: {$A}</p>";
?>
Results:
Notice: Undefined variable: A in /home/essma/public_html/global_test.php on line 3
This is A before functionA is called: .
This is A after functionA is called: Declared as global inside functionA
----
Server IP: 45.112.84.4
Probable Submitter: 45.91.157.134 (proxied: 136.38.151.185)
----
Manual Page -- https://php.net/manual/en/language.variables.scope.php
Edit -- https://main.php.net/note/edit/129208
Del: integrated -- https://main.php.net/note/delete/129208/integrated
Del: useless -- https://main.php.net/note/delete/129208/useless
Del: bad code -- https://main.php.net/note/delete/129208/bad+code
Del: spam -- https://main.php.net/note/delete/129208/spam
Del: non-english -- https://main.php.net/note/delete/129208/non-english
Del: in docs -- https://main.php.net/note/delete/129208/in+docs
Del: other reasons-- https://main.php.net/note/delete/129208
Reject -- https://main.php.net/note/reject/129208
Search -- https://main.php.net/manage/user-notes.php