函数($var)和函数()使用($var)之间有什么区别吗?


Is there any difference between function($var) and function() use ($var)?

它们之间有什么区别吗?

$something = function($var) { 
});
$something = function() use ($var) {
});

前者是具有名为 $var 的单个参数的函数。如果在脚本中的其他位置定义了另一个$var,则没关系;该函数不会在其作用域内(在其定义内)包含对它的引用。

例如。

$bar = 3;
function foo($bar) {
   if (isset($bar)) {
      echo "bar: $bar";
   } else {
      echo "no bar";
   } 
}
foo(10); // prints "bar: 10", because the function is called with the argument "10"
foo(); // prints "no bar" -- $bar is not defined inside the function scope

在后者的情况下,use $var闭包意味着在包含作用域中$var的定义可以在函数内部访问,就像全局变量一样。

例如

$bar = 3;
function foo($blee) use $bar {
   if (isset($bar)) {
      echo "bar: $bar";
   } else {
      echo "no bar";
   }
   if (isset($input)) {
      echo "input: $input";
   } else {
      echo "no input";
   }
}
foo(1); // prints "bar: 3, input: 1"
foo(); // prints "bar: 3, no input"

第一个是采用单个参数的函数,另一个是不包含参数并关闭父作用域中变量$var值的函数。