PHP function use variable from outside

前端 未结 4 1424
眼角桃花
眼角桃花 2020-11-30 00:08
function parts($part) { 
    $structure = \'http://\' . $site_url . \'content/\'; 
    echo($tructure . $part . \'.php\'); 
}

This function uses a

4条回答
  •  鱼传尺愫
    2020-11-30 00:55

    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:

    • Variable scope in PHP
    • Anonymous functions

提交回复
热议问题