0

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');

1 Answer 1

2
function($file = '') use ($attrs)
Sign up to request clarification or add additional context in comments.

1 Comment

You want return call_user_func_array($func, $args); in __call().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.