问题
I'm trying to get variables that I defined while in a function from another function I called in that function, example:
$thevar = 'undefined';
Blablahblah();
echo $thevar; (should echo blaaah)
function Blahedit(){
echo $thevar; (should echo blah)
$thevar = 'blaaah';
}
function Blablahblah(){
global $thevar;
$thevar = 'blah';
Blahedit();
}
I want to know if there's another way of doing this without passing down params to Blahedit(), get_defined_vars gives me vars within the function not $thevar... and calling global $thevar will just give me the previous unedited version.
Please help ):
回答1:
You can use this: http://php.net/manual/en/reserved.variables.globals.php
or better have a look at oop
http://php.net/manual/en/language.oop5.php http://php.net/manual/en/language.oop5.basic.php
回答2:
You can pass the variables as a reference parameter (shown below), encapsulate your code in a class and use your variable as class attribute or let the functions return the changed variable.
$thevar = 'undefined';
Blablahblah($thevar);
echo $thevar;
function Blahedit(&$thevar){
echo $thevar;
$thevar = 'blaaah';
}
function Blablahblah(&$thevar){
$thevar = 'blah';
Blahedit($thevar);
}
Using globals inside functions is considered to be a bad practice. However, passing a lot of variables by reference also is not good style.
If you want to get your code to work the way it is, you have to add a global $thevar
to your edit function:
function Blahedit(){
global $thevar;
echo $thevar; (should echo blah)
$thevar = 'blaaah';
}
回答3:
Just global $thevar inside blahedit.
function Blahedit(){
global $thevar;
echo $thevar; //(should echo blah)
$thevar = 'blaaah';
}
来源:https://stackoverflow.com/questions/14082589/php-accessing-variables-within-a-function-defined-in-another-function