I need to write some php recently, I have never written it before, I only know js. It seems that variables in PHP are not referenced by scope chains like JS. If the code below is like this, how to implement it?
<code>function A(){ $num = 0; function B(){ //这里如何引用到变量$num??? } }</code>
I checked and found that the global $num in B can refer to the global variable $num, but it seems that $num is not global. . . Please give me some advice.
I need to write some php recently, I have never written it before, I only know js. It seems that variables in PHP are not referenced by scope chains like JS. If the code below is like this, how to implement it?
<code>function A(){ $num = 0; function B(){ //这里如何引用到变量$num??? } }</code>
I checked and found that the global $num in B can refer to the global variable $num, but it seems that $num is not global. . . Please give me some advice.
Transfer:
JavaScript can use external variables directly in anonymous functions.
PHP anonymous functions cannot directly call the context variables of the code block by default. You need to use the use keyword to connect the closure (anonymous function) and external variables.
<code>function getMoney() { $rmb = 1; $dollar = 6; $func = function() use ( $rmb ) { echo $rmb; echo $dollar; }; $func(); } getMoney(); //输出: //1 //报错,找不到dorllar变量 </code>
As you can see, dollar is not declared in the use keyword, and it cannot be obtained in this anonymous function, so pay attention to this issue during development.
Some people may think whether it is possible to change the context variables in an anonymous function, but I found that it is not possible:
<code>function getMoney() { $rmb = 1; $func = function() use ( $rmb ) { echo $rmb; //把$rmb的值加1 $rmb++; }; $func(); echo $rmb; } getMoney(); //输出: //1 //1 </code>
It turns out that what use refers to is just a copy of the variable.
If you want to fully reference the variable instead of copying it, you need to add an & symbol in front of the variable:
<code>function getMoney() { $rmb = 1; $func = function() use ( &$rmb ) { echo $rmb; //把$rmb的值加1 $rmb++; }; $func(); echo $rmb; } getMoney(); //输出: //1 //2 </code>
If the anonymous function is returned to the outside world, the anonymous function will save the variables referenced by use, but the outside world cannot get these variables. In this way, the concept of 'closure' may be clearer:
<code>function getMoneyFunc() { $rmb = 1; $func = function() use ( &$rmb ) { echo $rmb; //把$rmb的值加1 $rmb++; }; return $func; } $getMoney = getMoneyFunc(); $getMoney(); $getMoney(); $getMoney(); //输出: //1 //2 //3 </code>
<code class="php">function A() { $num = 0; call_user_func(function () use ($num) { //这么用$num }); }</code>
The above answer is just to answer your question. You'd better read the manual first and be familiar with the basic syntax of PHP. Otherwise, if you encounter a question, just ask it once on the Q&A website, which is too inefficient. Never write it in js. php