php - 在另一个函数中定义的函数内访问变量?

时间:2012-12-29 14:28:27

标签: php function variables tags defined

我试图从我在该函数中调用的另一个函数中获取我在函数中定义的变量,例如:

$thevar = 'undefined';
Blablahblah();
echo $thevar; (should echo blaaah)
function Blahedit(){

     echo $thevar; (should echo blah)
     $thevar = 'blaaah';

}
function Blablahblah(){

     global $thevar;
     $thevar = 'blah';
     Blahedit();

}

我想知道是否有另一种方法可以在不将params传递给Blahedit()的情况下执行此操作,get_defined_vars在函数内给出了vars而不是$ thevar ...并且调用global $ thevar只会给我以前的未经编辑的版本。

请帮忙):

3 个答案:

答案 0 :(得分:0)

你可以用这个: http://php.net/manual/en/reserved.variables.globals.php

或者更好地看看oop

http://php.net/manual/en/language.oop5.php http://php.net/manual/en/language.oop5.basic.php

答案 1 :(得分:0)

您可以传递变量as a reference parameter(如下所示),将代码封装在类中,并将变量用作类属性,或让函数返回已更改的变量。

$thevar = 'undefined';
Blablahblah($thevar);
echo $thevar; 

function Blahedit(&$thevar){
     echo $thevar;
     $thevar = 'blaaah';
}

function Blablahblah(&$thevar){
     $thevar = 'blah';
     Blahedit($thevar);
}

在函数中使用全局变量被认为是一种不好的做法。但是,通过引用传递很多变量也不是好的风格。

如果您想让代码按原样运行,则必须在编辑功能中添加global $thevar

function Blahedit(){
     global $thevar;
     echo $thevar; (should echo blah)
     $thevar = 'blaaah';
}

答案 2 :(得分:0)

全球$ thevar里面的blahedit。

function Blahedit(){
    global $thevar;
    echo $thevar; //(should echo blah)
    $thevar = 'blaaah';

}
相关问题