php - define anonymous function using values from current scope? -


i trying create anonymous function need access variables current scope in it's definition:

class test { private $types = array('css' => array('folder' => 'css')); public function __construct(){ //define our asset types foreach($this->types $name => $attrs){ $this->{$name} = function($file = ''){ //this line falls over! //undefined variable $attrs! return '<link href="'.$attrs['folder'].'/'.$file.'" />'; } } } } $assets = new test(); 

obviously example very minimalistic gets across trying do. so, question is, how can access parent scope definition of function? (once defined don't need context when function called).


edit #1

ok after using matthew's answer have added use below; issue when call function no output.

if add die('called') in function produced, not if echo or return something.

class test { private $types = array('css' => array('folder' => 'css')); public function __construct(){ //define our asset types foreach($this->types $name => $attrs){ $this->{$name} = function($file = '') use ($attrs){ //this line 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 , without "return" return $func($args); } } } $assets = new test(); echo 'output: '.$assets->css('lol.css'); 

function($file = '') use ($attrs) 

Comments

Popular posts from this blog

javascript - backbone.js Collection.add() doesn't `construct` (`initialize`) an object -

php - Get uncommon values from two or more arrays -

Adding duplicate array rows in Php -