标签:
function () use ($x, &$y){}
自从PHP5.3开始有了closure/匿名函数的概念,在这里的use关键词的作用是允许匿名函数capture到父函数scope
内存在的$x和$y变量。其中&&y为引用方式capture,也就是说每次该匿名函数调用时,y的值如果
被修改了也反映在这里,而$x则是静态引用。
<?php $message = "hello\n"; $example = function () { echo $message; }; // Notice: Undefined variable: message $example(); $example = function () use ($message) { echo $message; }; // "hello" $example(); // Inherited variable‘s value is from when the function is defined, not when called $message = "world\n"; // "hello" $example(); // Inherit by-reference $message = "hello\n"; $example = function () use (&$message) { echo $message; }; // "hello" $example(); // The changed value in the parent scope is reflected inside the function call $message = "world\n"; // "world" $example(); // Closures can also accept regular arguments $example = function ($arg) use ($message) { echo $arg . ‘ ‘ . $message; }; // "hello world" $example("hello");
标签:
原文地址:http://www.cnblogs.com/kidsitcn/p/5370369.html