Pregunta

I am building a menu with pricing loaded by calling array keys. Menu displays but I can't get the values to show in the price section.

I loaded an associative array and am looking to call its values from inside a function. I've declared global scope, and am using heredoc to add the values to the table. I'm also attempting to call the printMenu() function by encapsulation. Prices are showing inside the menu ONLY when the code has NOT been placed inside function.

Don't know what's wrong here. Help please!

    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;
    }
¿Fue útil?

Solución

You have to declare your variable before you're calling a function with your global variable:

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

printMenu();

Also maybe you will consider to set this variable as argument in your function. Check this:

function printMenu($argName) {
   var_dump($argName);
}

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

printMenu($plain);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top