如何在不传递变量的情况下访问函数中的变量


How do I access a variable in a function without passing it?

我环顾四周,但真的找不到任何东西。我尝试使用全局,但我认为我用错了。

function testing() {
    $a = (object) array('a' => 100, 'b' => 200);
    function test2(){
        global $a;
        var_dump($a);
    }
    test2();
}
testing();

我希望能够在 test2() 中获取$a而无需将变量作为参数传递。

编辑:感谢您的评论和回答。这些示例有效,但是在我的特定情况下,它似乎不起作用。我在视图的顶部编写了这个小函数,然后在需要时调用它。

var_dump($data); // DATA here is fine - I need it in the function
function getDataVal($data_index) {
    return (isset($data->{$data_index}))?$data->{$data_index}:'';
}

然后我稍后在页面上调用它,如下所示:

<input type="text" id="something" value="<?=getDataVal('something')?>" />

我知道我可以在请求中传递$data,但是我希望有一种更简单的方法来访问该函数中的数据。

全局表示"全局",例如在全局命名空间中定义的变量。

我不知道你为什么要避免将变量作为参数传递。我的猜测:它应该是可写的,而且通常不是。

以下是同一解决方案的两种变体:

<?php

// VARIANT 1: Really globally defined variable
$a = false; // namespace: global
function testing1() {
    global $a;
    $a = (object) array('a' => 100, 'b' => 200);
    function test1(){
        global $a;
        echo '<pre>'; var_dump($a); echo '</pre>'; 
    }
    test1();
}
testing1();

// VARIANT 2: Passing variable, writeable
function testing2() {
    $a = (object) array('a' => 100, 'b' => 200);
    function test2(&$a){ // &$a: pointer to variable, so it is writeable
        echo '<pre>'; var_dump($a); echo '</pre>'; 
    }
    test2($a);
}
testing2();

}
testing();

结果,两个变体:

object(stdClass)#1 (2) {
  ["a"]=> int(100)
  ["b"]=> int(200)
}
object(stdClass)#2 (2) {
  ["a"]=> int(100)
  ["b"]=> int(200)
}

将其定义为全局变量:

    a = array();
    function testing() {
        global $a;
        $a = (object) array('a' => 100, 'b' => 200);
        function test2(){
            global $a;
            var_dump($a);
        }
        test2();
    }
testing();

编辑global a中缺少的$

相关文章: