PHP function use variable from outside

前端 未结 4 1405
眼角桃花
眼角桃花 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:44

    Alternatively, you can bring variables in from the outside scope by using closures with the use keyword.

    $myVar = "foo";
    $myFunction = function($arg1, $arg2) use ($myVar)
    {
     return $arg1 . $myVar . $arg2;
    };
    
    0 讨论(0)
  • 2020-11-30 00:46

    Do not forget that you also can pass these use variables by reference.

    The use cases are when you need to change the use'd variable from inside of your callback (e.g. produce the new array of different objects from some source array of objects).

    $sourcearray = [ (object) ['a' => 1], (object) ['a' => 2]];
    $newarray = [];
    array_walk($sourcearray, function ($item) use (&$newarray) {
        $newarray[] = (object) ['times2' => $item->a * 2];
    });
    var_dump($newarray);
    

    Now $newarray will comprise (pseudocode here for brevity) [{times2:2},{times2:4}].

    On the contrary, using $newarray with no & modifier would make outer $newarray variable be read-only accessible from within the closure scope. But $newarray within closure scope would be a completelly different newly created variable living only within the closure scope.

    Despite both variables' names are the same these would be two different variables. The outer $newarray variable would comprise [] in this case after the code has finishes.

    0 讨论(0)
  • 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
    0 讨论(0)
  • 2020-11-30 01:01

    Just put in the function using GLOBAL keyword:

     global $site_url;
    
    0 讨论(0)
提交回复
热议问题