I am trying to create an anonymous function but need to access variables from the 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 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();
Obviously this example is very very minimalistic but it gets across what I am trying to do. So, my question is, How can I access the parent scope only for the definition of the function? (once defined I obviously don't need that context when the function is called).
Edit #1
Ok so after using Matthew's answer I have added use
as below; but now my issue is that when I call the function I get no output.
If i add a die('called')
in the function then that is produced, but not if I echo or return something.
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');