Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

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

2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

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.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report