php - Accessing variables within a function defined in another function?

落花浮王杯 提交于 2019-12-25 06:34:05

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!