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

时间:2016-02-26 10:08:09

标签: php scope

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

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

我希望能够在不将变量作为参数传递的情况下在test2()中获取$。

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

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,但我希望有一种更简单的方法来访问该函数内的数据。

2 个答案:

答案 0 :(得分:1)

global 表示&#34; global&#34;,例如全局命名空间中定义的变量。

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

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

<?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)
}

答案 1 :(得分:0)

将其定义为全局变量:

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

testing();

修改 global a

中缺少$
相关问题