note 130412 added to language.variables.scope

From: Date: Thu, 10 Jul 2025 06:54:18 +0000
Subject: note 130412 added to language.variables.scope
Groups: php.notes 
Request: Send a blank email to php-notes+get-222266@lists.php.net to get a copy of this message
If you're a JavaScript programmer who came to the "Variable scope" manual page trying to figure out how to do a closure in PHP: 1. What JavaScript refers to as a "closure", is in PHP just called "inheriting variables from the parent scope" 2. In PHP, the term "closure" instead refers to the class that anonymous functions are instances of. 3. Unlike in JavaScript, you don't get access to any of the variables of the parent scope (or the global scope) automatically, except for superglobals. 4. ... except for arrow functions (in PHP they start with "fn() => "), which *do* automatically inherit variables from their parent scope. 5. For anonymous functions (i.e. functions assigned to a variable), you can add a "use" clause to access specific variables from the parent scope. Here's an example: <?php function outer() { $outervar = 1; // Each inherited variable must be listed in the "use" clause $anonfn = function($param1) use ($outervar) { return $param1 + $outervar; } return $anonfn; } ?> 6. Normal functions (i.e. not assigned to a variable) are globally scoped, so there is no non-global "parent scope" to inherit from. ---- Server IP: 45.112.84.4 Probable Submitter: 80.90.5.137 (proxied: 2407:7000:98d8:6600:6ee4:2fff:28b9:3770) ---- Manual Page -- https://php.net/manual/en/language.variables.scope.php Edit -- https://main.php.net/note/edit/130412 Del: integrated -- https://main.php.net/note/delete/130412/integrated Del: useless -- https://main.php.net/note/delete/130412/useless Del: bad code -- https://main.php.net/note/delete/130412/bad+code Del: spam -- https://main.php.net/note/delete/130412/spam Del: non-english -- https://main.php.net/note/delete/130412/non-english Del: in docs -- https://main.php.net/note/delete/130412/in+docs Del: other reasons-- https://main.php.net/note/delete/130412 Reject -- https://main.php.net/note/reject/130412 Search -- https://main.php.net/manage/user-notes.php

« previous php.notes (#222266) next »