note 117267 deleted from language.variables.scope by crell
| From: | crell@php.net | Date: | Thu, 31 Mar 2022 19:42:45 +0000 |
| Subject: | note 117267 deleted from language.variables.scope by crell | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-217937@lists.php.net to get a copy of this message | ||
Note Submitter: zweibieren at yahoo dot com
----
Take to heart this hard-won rule:
Declare AT THE TOP any variable that is to be global.
Both at the top of the FILE
AND at the top of any FUNCTION where it appears.
Why AT THE TOP? So it is sure to be declared before use. Otherwise a non-global version of the
variable will be created and your code will fail.
Why at the top of a FUNCTION? Because otherwise the function will refer only to its local version of
the variable and your code will fail.
Why at the top of the FILE? Because someday--a day that you cannot now imagine--you will want to
"include" the file. And when you do, instances of the variable outside functions will not
go in the global scope and your code will fail. (When the "include" is inside a calling
function, variables in the included file go into the scope of the calling function.)
Example file where variable $x is used outside and inside functions:
|<!DOCTYPE html ...>
|<html xmlns ...>
| <?php global $x; ?>
|<head>
| Some html headers
| <?php
| $x = 1;
| function bump_x() {
| global $x;
| $x += 1;
| }
| ?>
|</head>
|<body>
| More html
| <?php echo $x; bump_x(); ?>
| Yet more html.
|</body>
</html>