Home php does not change the global variable PHP

does not change the global variable PHP

Author

Date

Category

Tell me why the global variable a does not change, and is it possible to somehow change it in this design when the call goes inside an anonymous function.

$ a = 1;
$ b = function () use ($ a) {
  FUNCTION C ()
  {
    Global $ a;
    $ a ++;
  }
  echo ($ a. '& lt; / br & gt;');
  c ();
  echo ($ a. '& lt; / br & gt;');
};
$ B ();

Answer 1, Authority 100%

You create an anonymous function and inherit the variable from the global area. In your case, when you try it to change, a copy is created. To change the original to inherit the link.

$ b = function () use (& amp; $ a) {

ADD
In general, it looks somewhat different. The C function in reality changes the value of the global $ a . You can make sure that if you call as previously your $ b () and then next C () (you declare it globally during the call of anonymous). You will see what will be displayed 1,1,3
But Echo $ A you displays a captured copy by value, so it does not see changes. So in this particular case, to see the changes you need to inherit it by reference. I repeat “To see,” and not “to change”, for everything changes.

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions