Why are my variables going out of scope? PHP

后端 未结 2 1307
清酒与你
清酒与你 2021-01-22 20:49

Language is PHP 5.4 on an Apache 2.2 server. It\'s a script being called by ajax.

$usr = new User();

function getMyName(){
    echo $usr->username;
}
getMyNa         


        
相关标签:
2条回答
  • 2021-01-22 21:07

    It's not ridiculous. This is how variable scope is supposed to work. You need to pass your $usr variable in as a function parameter, otherwise it'll be out of scope. Functions were designed to take in input and send back a result/output. You should stick with your second example, instead of messing around with globals...

    $usr = new User();
    $name = $usr->username;
    
    function getMyName($n){
        echo $n;
    }
    getMyName($name);
    

    Here's a quote from Wikipedia:

    In computer science, a subroutine, also termed procedure, function, routine, method, or subprogram, is a part of source code within a larger computer program that performs a specific task and is relatively independent of the remaining code.

    0 讨论(0)
  • 2021-01-22 21:09
    $usr = new User();
    
    function getMyName(){
        global $usr;
        echo $usr->username;
    }
    getMyName();
    

    alternatively:

    $usr = new User();
    
    function getMyName($usr){
        echo $usr->username;
    }
    getMyName($usr);
    
    0 讨论(0)
提交回复
热议问题