note 117267 added to language.variables.scope

From: Date: Tue, 12 May 2015 18:32:33 +0000
Subject: note 117267 added to language.variables.scope
Groups: php.notes 
Request: Send a blank email to php-notes+get-202507@lists.php.net to get a copy of this message
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> ---- Server IP: 72.52.91.14 Probable Submitter: 24.131.255.144 ---- Manual Page -- http://php.net/manual/en/language.variables.scope.php Edit -- https://master.php.net/note/edit/117267 Del: integrated -- https://master.php.net/note/delete/117267/integrated Del: useless -- https://master.php.net/note/delete/117267/useless Del: bad code -- https://master.php.net/note/delete/117267/bad+code Del: spam -- https://master.php.net/note/delete/117267/spam Del: non-english -- https://master.php.net/note/delete/117267/non-english Del: in docs -- https://master.php.net/note/delete/117267/in+docs Del: other reasons-- https://master.php.net/note/delete/117267 Reject -- https://master.php.net/note/reject/117267 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#202507) next »