2

I am afraid I have a beginners PHP question. I am using Symfony's Cache component. https://symfony.com/doc/current/components/cache.html

I am calling the cache object inside of a function which receives 2 arguments ($url, $params).

class MainController extends AbstractController {
    public function do($url, $params) {
        $cache = new FilesystemAdapter();
        return $cache->get('myCacheName', function (ItemInterface $c) {
            global $url;
            var_dump($url); // ---> null !!!!
        }
    }
}

My problem is, that I cannot access the function arguments inside of the cache method call. $url and $params is null. Of course I could use public class variables in class MainController to send the variables back ad forth, but this seems to be a bit clumsy.

ESP32
  • 8,089
  • 2
  • 40
  • 61
  • 5
    just use `use` in the closure to import the `$url`, ala `->get(arg1, function() use ($url) {` – Kevin May 02 '19 at 08:09
  • 1
    Possible duplicate of [PHP Closures scoping of variables](https://stackoverflow.com/questions/18621297/php-closures-scoping-of-variables) – Mike Doe May 02 '19 at 08:10

1 Answers1

6

In PHP a closure does not have access to variables outside of its scope by default, you have to use those like so:

return $cache->get('myCacheName', function (ItemInterface $c) use ($url) {
    var_dump($url); // ---> no longer null !!!!
}