0

PHP で関数を使用することについて学習しようとしています: 値 0 で変数を開始し、代入演算子を使用して変数に追加したい場合、関数内でどのように行うのですか? 言葉で説明するのはちょっと難しいので、以下に例を示します。

<?php
function tally($product){

  // I want these to be the starting values of these variables (except for $tax, which will remain constant)
  $tax = 0.08;
  $total_price = 0;
  $total_tax = 0;
  $total_shipping = 0;
  $grand_total = 0;

  // So, the program runs through the function:

  if($product == 'Candle Holder'){
    $price = 11.95;
    $shipping = 0;
    $total_price += $price;
    $total_tax += $tax * $price;
    $total_shipping += $shipping * $price;
    $grand_total = ($total_price + $total_tax + $total_shipping);
  }
  else if($product == 'Coffee Table'){
    $price = 99.50;
    $shipping = 0.10;
    $total_price += $price;
    $total_tax += $tax * $price;
    $total_shipping += $shipping * $price;
    $grand_total = ($total_price + $total_tax + $total_shipping);
  }
  else if($product == 'Floor Lamp'){
    $price = 44.99;
    $shipping = 0.10;
    $total_price += $price;
    $total_tax += $tax * $price;
    $total_shipping += $shipping * $price;
    $grand_total = ($total_price + $total_tax + $total_shipping);
  }else{
    echo '<li>Missing a product!</li>';
  }
  // And then, it echoes out each product and price:
  echo '<li>'.$product.': $'.$price;
  // To test it, I echo out the $grand_total to see if it's working:
  echo '<br>---'.$grand_total;
} //end of function tally()

// End of the function, but every time I call
tally('Candle Holder');
tally('Coffee Table');
tally('Floor Lamp');
?>

3 つの製品すべての $grand_total には加算されません。関数が先頭 (上部) まで実行され、$grand_total が 0 にリセットされるためだとわかっています。元の値の変数を関数の外に配置しようとすると、ブラウザーはエラーを返します: undefined variable.

これがごちゃごちゃしていることはわかっているので、さらに情報を提供する必要があるかどうか教えてください. ありがとう!

編集


それを単純化する別の方法を見つけました。関数を完全に忘れていましたreturn

<B>Checkout</B><br>
Below is a summary of the products you wish to purchase, along with totals:
<?php

function tally($product, $price, $shipping){

$tax = 0.08;

    $total_tax = $tax * $price;
    $total_shipping = $shipping * $price;
    $grand_total = ($total_price + $total_tax + $total_shipping);

echo '<li>'.$product.': $'.$grand_total;
return $grand_total;

} //end of function tally()

?>
<ul>
<?php
    $after_tally = tally('Candle Holder', 11.95, 0);
    $after_tally += tally('Coffee Table', 99.50, 0.10);
    $after_tally += tally('Floor Lamp', 49.99, 0.10);

?>
</ul>
<hr>
<br>
<B>Total (including tax and shipping): $<? echo number_format($after_tally, 2); ?></B>

私が望んでいたことを正確に行います!助けてくれてありがとう!配列がこれに役立つことは知っていますが、私は今、レッスンでそれに取り組んでいます。

4

4 に答える 4