Search code examples
phpfunctionvariables

PHP function use variable from outside


function parts($part) { 
    $structure = 'http://' . $site_url . 'content/'; 
    echo($tructure . $part . '.php'); 
}

This function uses a variable $site_url that was defined at the top of this page, but this variable is not being passed into the function.

How do we get it to return in the function?


Solution

  • Add second parameter

    You need to pass additional parameter to your function:

    function parts($site_url, $part) { 
        $structure = 'http://' . $site_url . 'content/'; 
        echo $structure . $part . '.php'; 
    }
    

    In case of closures

    If you'd rather use closures then you can import variable to the current scope (the use keyword):

    $parts = function($part) use ($site_url) { 
        $structure = 'http://' . $site_url . 'content/'; 
        echo $structure . $part . '.php'; 
    };
    

    global - a bad practice

    This post is frequently read, so something needs to be clarified about global. Using it is considered a bad practice (refer to this and this).

    For the completeness sake here is the solution using global:

    function parts($part) { 
        global $site_url;
        $structure = 'http://' . $site_url . 'content/'; 
        echo($structure . $part . '.php'); 
    }
    

    It works because you have to tell interpreter that you want to use a global variable, now it thinks it's a local variable (within your function).

    Suggested reading: