Differences between getting external variables using PHP closures and declaring variables using global keywords

Source: Internet
Author: User

Differences between getting external variables using PHP closures and declaring variables using global keywords

Recently, when I was learning workerman, I had frequent access to callback functions. I often use different worker usage methods to call external worker variables in these two different ways, here we will sort out the differences between getting external variables with the PHP closure and declaring variables with the global keyword.

Closure

Closure is a common concept. We can usually use it with the callback function to make the code more concise and easy to read.

The closure allows the function to use variables in the parent scope by copying them. For example:

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

Global keyword declaration variable

Variables declared through global can also make the function body call variables outside the function. However, unlike global and use, the globle keyword will create a reference with the same name as the external variable, in addition, modifications to variables in the function also apply to external variables.

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

This is just to create a reference with the same name and will not change the scope of the original external variable $ global. That is to say, to call this function in another function, you still need to declare or use the 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*/

Modify the Code a bit to make it easier to compare the differences between the closure and global keyword declaration variables for accessing external variables.

<?php$global = 'hello';$fun = function(){  global $global;  $global ='world';  echo 'a:'.$global."\n";};$bbb = function()use($global){  $global = 'china';  echo 'c:'.$global."\n";};$fun();echo 'b:'.$global."\n";$bbb();echo 'd:'.$global;

Here, the outputs B and d show that global changes the value of the external variable, but the closure method does not.

Output:

a: worldb: worldc:chinad: world

Finally, I will post an example of the typical use of anonymous functions in the official document. The closure works with the callback function:

class Cart{  const PRICE_BUTTER = 1.00;  const PRICE_MILK  = 3.00;  const PRICE_EGGS  = 6.95;  protected  $products = array();  public function add($product, $quantity)  {    $this->products[$product] = $quantity;  }  public function getQuantity($product)  {    return isset($this->products[$product]) ? $this->products[$product] :      FALSE;  }  public function getTotal($tax)  {    $total = 0.00;    $callback =      function ($quantity, $product) use ($tax, &$total)      {        $pricePerItem = constant(__CLASS__ . "::PRICE_" .          strtoupper($product));        $total += ($pricePerItem * $quantity) * ($tax + 1.0);      };    array_walk($this->products, $callback);    return round($total, 2);  }}$my_cart = new Cart;$my_cart->add('butter', 1);$my_cart->add('milk', 3);$my_cart->add('eggs', 6);print $my_cart->getTotal(0.05) . "\n";

Summary

The above section describes the differences between PHP closures used to obtain external variables and global keyword declaration variables. I hope this will be helpful to you. If you have any questions, please leave a message, the editor will reply to you in a timely manner. Thank you very much for your support for the help House website!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.