【问题标题】:How do I access a variable in a function without passing it?如何在不传递函数的情况下访问函数中的变量?
【发布时间】:2016-02-26 10:08:08
【问题描述】:

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

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

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

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

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 scope


【解决方案1】:

global 表示“全球”,例如全局命名空间中定义的变量。

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

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

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

【讨论】:

  • 感谢您抽出宝贵时间回答我的问题。我已经更新了我的问题。
【解决方案2】:

定义为全局变量:

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

testing();

编辑global a中缺少$

【讨论】:

    猜你喜欢
    • 2022-01-15
    • 2013-10-19
    • 1970-01-01
    • 2020-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多