Get the App
SLTechnology News&Howtos  ›  Development  › 

The difference between PHP closure getting external variables and global keyword declaring variables

Shulou Source: shulou.com Published: 2022-06-03 19:57:06 10月07日 Update

This article mainly explains "the difference between PHP closure obtaining external variables and global keyword declaration variables". The explanation in this article is simple and clear, easy to learn and understand. Please follow the ideas of Xiaobian and go deep into it. Study and learn "the difference between PHP closure obtaining external variables and global keyword declaration variables" together!

closure

Closures are a common concept, and we can often use them with callback functions to make our code simpler and easier to read.

Closures can be copied to make a function use variables in the parent scope. For example:

$global = 'hello';$bbb = function()use($global){ echo $global. "\n";};$bbb();//output 'hello'

global keyword declaration variable

The global variable declaration also allows the function body to call variables outside the function, but unlike use, the global keyword creates a reference to the external variable with the same name, and changes to variables within the function also scope external variables.

$global = 'hello';$fun = function(){ global $global; $global =' world'; echo $global. "\n";};$fun();//output 'world'

This just creates a reference with the same name and does not change the scope of the original external variable $global, which means that calling it in another function still requires declaration or closure.

$global = 'hello';$fun = function(){ global $global; $global =' world'; echo 'a:'.$ global. "\n";};$ccc = function(){ echo 'b:'.$ global;};$fun()$ccc()/*

output

a: worldNotice: Undefined variable: global in xxxxxxx on line xx*/

A slight change in the code makes it easier to compare closures with global keyword declarations, two ways to access external variables.

Tags: Variables closures functions keywords keywords output function way learning code content can make different concise two that is examples originally just Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Linux Apple NVidia Shulou Tech Info Huawei