search

Home  >  Q&A  >  body text

PHP nested function and anonymous function scope issues

function a()
{
    $demi = '局部变量';
    b($demi);
}
function b($args)
{
    echo $args;
}
a();

All functions and classes in PHP have global scope and can be defined within a function and called outside, and vice versa.

Why can function b obtain the local variables of function a by passing parameters?

function tesxt()
{
    $var = 10;
    $echonumber = function($num) {
         echo $num;
    };
    $echonumber($var);
}
tesxt();

Similarly, why do anonymous functions also obtain variables of external functions by passing parameters?

phpcn_u1582phpcn_u15822775 days ago629

reply all(1)I'll reply

  • 高洛峰

    高洛峰2017-05-18 10:47:34

    That’s actually the case. When you call a function, the parameter you pass is actually a copy, and the value is copied, which is equivalent to another variable and has no relationship.
    The same goes for anonymous functions. But if you want to use external variables in anonymous functions, they cannot be accessed.

    reply
    0
  • Cancelreply