【问题标题】:Global array declared inside function, but values not showing when called在函数内部声明的全局数组,但在调用时未显示值
【发布时间】:2013-11-05 22:01:07
【问题描述】:

我正在构建一个通过调用数组键加载定价的菜单。菜单显示,但我无法在价格部分显示值。

我加载了一个关联数组,并希望从函数内部调用它的值。我已经声明了全局范围,并且正在使用 heredoc 将值添加到表中。我也试图通过封装调用 printMenu() 函数。仅当代码未放置在功能内时,价格才会显示在菜单内。

不知道这里出了什么问题。请帮忙!

    printMenu();

    $plain = array(
      "small" => "3.50",
      "medium" => "6.25",
      "large" => "8.00"
    );

    function printMenu() {
      global $plain;
      print <<<HERE
        <table>
          <tr>
           <th>&nbsp;</th>
           <th class = "pSize">Small</th>
           <th class = "pSize">Med</th>
           <th class = "pSize">Large</th>
          </tr>
          <tr>
           <th>Plain</th>
           <td class ="price">$plain[small]</td>
           <td class ="price">$plain[medium]</td>
           <td class ="price">$plain[large]</td>
          </tr>
        </table>
    HERE;
    }

【问题讨论】:

    标签: php arrays global heredoc


    【解决方案1】:

    在使用全局变量调用函数之前,您必须声明变量:

    $plain = array(
      "small" => "3.50",
      "medium" => "6.25",
      "large" => "8.00"
    );
    
    printMenu();
    

    也许您还会考虑将此变量设置为函数中的参数。检查这个:

    function printMenu($argName) {
       var_dump($argName);
    }
    
    $plain = array(
      "small" => "3.50",
      "medium" => "6.25",
      "large" => "8.00"
    );
    
    printMenu($plain);
    

    【讨论】:

    • 我考虑过,但我有四个数组(即 $plain、$vegetarian、$pepperoni、$hawaiian)。我只提供了一个数组作为解决一个的问题应该是四个的解决方案,输入一张表。正确的?谢谢你。第一次回复我的一个帖子。我想我是 stackoverflow 的忠实拥护者,除了我不能赞成你的解决方案。希望贡献一个答案...有一天=/
    • 我不知道我是否正确,但请查看文档上的 array_merge。你不能赞成我的回答,因为你是这里的新人。目前,您只能将问题中的答案勾选为“已接受”。
    猜你喜欢
    • 1970-01-01
    • 2019-05-09
    • 2014-01-17
    • 2011-10-11
    • 1970-01-01
    • 2012-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多