PHP function use variable from outside

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:

Leave a Comment