note 119366 deleted from language.variables.scope by crell
| From: | crell@php.net | Date: | Thu, 31 Mar 2022 19:32:27 +0000 |
| Subject: | note 119366 deleted from language.variables.scope by crell | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-217915@lists.php.net to get a copy of this message | ||
Note Submitter: Ganlv
----
<?php
$var = 1;
function foo() {
$var = &$GLOBALS['var'];
var_dump($var);
}
function bar() {
global $var; // they are the same.
var_dump($var);
}
foo();
bar();
var_dump($var);
?>
In a function, 'global $var;' is to declare a local variant, and the local $var has the
same reference to the global $var.
<?php
$var = 1;
function foo() {
global $var;
unset($var); // unset local $a, the global $a is still there.
var_dump($var); // Undefined variable: var
var_dump($GLOBALS['var']); // this is ok.
}
foo();
var_dump($var); // this is ok.
?>
<?php
$var = 1;
function bar() {
global $var;
unset($GLOBALS['var']); // unset global $a, the local $a is still here.
var_dump($var); // this is ok.
var_dump($GLOBALS['var']); // Undefined index: var
}
foo();
var_dump($var); // Undefined variable: var
?>
'unset($var);' is like 'var = NULL;'(var is a pointer) in the C language,
instead of 'free(var);'