我正在尝试创建一个匿名函数,但需要从其定义中的当前范围访问变量:
class test {
private $types = array('css' => array('folder' => 'css'));
public function __construct(){
//define our asset types
foreach($this->types as $name => $attrs){
$this->{$name} = function($file = ''){
//this line is where is falls over!
//undefined variable $attrs!
return '<link href="'.$attrs['folder'].'/'.$file.'" />';
}
}
}
}
$assets = new test();
显然,这个例子非常简约,但它涵盖了我想要做的事情。所以,我的问题是,我怎样才能只为函数的定义访问父作用域?(一旦定义,当函数被调用时,我显然不需要那个上下文)。
编辑#1
好的,在使用马修的回答后,我添加use
了如下内容;但现在我的问题是,当我调用该函数时,我没有得到任何输出。
如果我在函数中添加 a die('called')
,那么它会产生,但如果我回显或返回某些东西则不会。
class test {
private $types = array('css' => array('folder' => 'css'));
public function __construct(){
//define our asset types
foreach($this->types as $name => $attrs){
$this->{$name} = function($file = '') use ($attrs){
//this line is where is falls over!
//undefined variable $attrs!
return '<link href="'.$attrs['folder'].'/'.$file.'" />';
}
}
}
public function __call($method, $args)
{
if (isset($this->$method) === true) {
$func = $this->$method;
//tried with and without "return"
return $func($args);
}
}
}
$assets = new test();
echo 'output: '.$assets->css('lol.css');