在函数内声明的全局数组,但调用时不显示值


Global array declared inside function, but values not showing when called

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

我加载了一个关联数组,并希望从函数内部调用其值。我已经声明了全局范围,并且正在使用 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;
    }

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

$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);