Search code examples
phpglobal-variablesrouterdispatch

Passing global variables to dispatch router library php


So I'm using noodlehaus / dispatch for my website routhing. I want to pass some variables from main scope like $currentLang to route(...), but I get this error:

Notice: Undefined variable: currentLang in C:\xampp\htdocs\_PERSONAL\newSite\index.php on line 18

Here's a part of my code.

require './functions/dispatch.php';

$currentLang = 'en';

route('GET', '/resume', function () {
    $data['lang'] = $currentLang;

    return response(
        phtml(__DIR__.'/views/resume', ['data' => $data ])
    );
});

dispatch();

Please help me with this. Thanks.


Solution

  • adding global $data; solved the problem:

        require './functions/dispatch.php';
    
        $currentLang = 'en';
    
        route('GET', '/resume', function () {
            global $currentLang;
            $data['resume'] = json_decode(
                file_get_contents("assets/json/resume-".$currentLang.".json"), true
            );
    
            return response(
                phtml(__DIR__.'/views/resume', ['data' => $data ])
            );
        });
    

    Or like this:

        require './functions/dispatch.php';
    
        $currentLang = 'en';
    
        route('GET', '/resume', function () use ($currentLang){
            $data['resume'] = json_decode(
                file_get_contents("assets/json/resume-".$currentLang.".json"), true
            );
    
            return response(
                phtml(__DIR__.'/views/resume', ['data' => $data ])
            );
        });