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
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.
$usr = new User();
function getMyName(){
global $usr;
echo $usr->username;
}
getMyName();
alternatively:
$usr = new User();
function getMyName($usr){
echo $usr->username;
}
getMyName($usr);