【问题标题】:variables outside/inside of a function: PHP beginner函数外部/内部的变量:PHP初学者
【发布时间】:2013-11-10 11:02:58
【问题描述】:

尝试了解如何在 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');
?>

它不会添加到所有三种产品的 $grand_total 中。 我知道这是因为函数从开头(顶部)运行并将 $grand_total 重置为 0。如果我尝试将原始值变量放在函数之外,浏览器会返回错误:未定义变量。

我知道这很混乱,所以请告诉我是否需要提供更多信息。 谢谢!

编辑


找到了另一种简化它的方法。完全忘记了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>

完全符合我的要求! 谢谢您的帮助!我知道数组可以帮助解决这个问题,但我现在才刚刚在我的课程中谈到这一点。

【问题讨论】:

  • 对您的函数的调用的每次迭代一次只能处理一个产品,因此您的总计将永远是单个产品的价值,因此即使您的输入中有 30 个产品,它也会只在你能做的就是传递一个输入数组通过它时才运行它,我会用更多细节给出一个完整的答案。
  • 我建议你去学习PHP中的OOP编程。这样,你会比现在舒服得多。特别是对于您的产品篮子。
  • 听起来不错,感谢您的建议! Nettuts+有课程,我正在考虑参加。

标签: php function variables if-statement assignment-operator


【解决方案1】:

其他人所说的问题是范围。在您使用代码的情况下,可能使用静态变量(不是首选),将 true 作为第二个参数传递以将 $grand_total 重置为 0:

function tally($product, $reset=false)
{
    //your vars
    static $grand_total = 0;

    if($reset) {
        $grand_total = 0;
    }

    //your code

    return $grand_total;
}

最好只返回 $grand_total 并将其汇总到调用该函数的代码中。

但是,我会考虑使用对象。至少,将产品和价格添加到可以包含的文件中的数组中,然后在需要时循环:

$tax = 0.08;

$products = array(
    'Candle Holder' => array(
        'price' => 11.95,
        'shipping' => 0,
    ),
    'Coffee Table' => array(
        'price' => 99.50,
        'shipping' => .10,
    ),
);

$grand_total = 0;

foreach($products as $product => $values) {
    $total = $values['price'] + ($tax * $values['price']) + ($values['price'] * $values['shipping']);
    $grand_total += $total;
    echo '<li>'.$product.': $'.$values['price'];
}

【讨论】:

    【解决方案2】:
    <?php
    
    $input_product_array = array("Candle Holder","Coffee Table");
    
    function tally($incomingarray){
    
    $tax = 0.08;
    $total_price = 0;
    $total_tax = 0;
    $total_shipping = 0;
    $grand_total = 0;
    
    $return_product_array = array(); // we're doing this so we can return multiple product row entries and a single grand total it'll make sense shortly
    
    foreach ($incomingarray as $key=>$productname) {
    
    if($productname == '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);
        $return_product_array[] = '<li>'.$productname .': $'.$price.'</li>';
    } else if($productname == '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);
        $return_product_array[] = '<li>'.$productname .': $'.$price.'</li>';
    } else if($productname == '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);
        $return_product_array[] = '<li>'.$productname .': $'.$price.'</li>';
    } 
    
    }
    //now we construct a final return array which contains all of our products array in one entry and then the grandtotal/totalprice/totaltax/total shipping in other columns
    
    $returnarray = array($return_product_array,$grand_total,$total_shipping,$total_tax,$total_price);
    
    return $returnarray;
    
    }
    
    
    $returnedinfo = tally($input_product_array);
    
    //now we can spit out our products
    foreach ($returnedinfo[0] as $key=>$productlist) { // always going to be an array returned from function and element 0 will always be items
        echo $productlist;  
    }
    
    
    echo "totals<br />";
    echo "Pre-Tax Total = $".$returnedinfo[4];
    echo "Total Tax = $".$returnedinfo[3];
    echo "Total Shipping = $".$returnedinfo[2];
    echo "Grand Total = $".$returnedinfo[1];
    ?>
    

    类似的东西

    【讨论】:

      【解决方案3】:

      您需要了解范围。除非您将它们传递给函数或在函数中将它们全球化,否则函数无法访问标准变量。理想情况下,您将所需的内容传递给函数。

      在您的情况下,您期望一个函数 - 一个独立的进程 - 作为一个不断运行的程序......或类似的东西。也许您需要做的是重新考虑您对tally($product) 的期望...

      <?php
      function tally($product)
      {
          $tax = 0.08;
          $total_price = 0;
          $total_tax = 0;
          $total_shipping = 0;
          $grand_total = 0;
      
          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);
          }
      
          return $grand_total;
      }
      
      $grand_total = 0;
      $grand_total += tally('Candle Holder');
      $grand_total += tally('Floor Lamp');
      
      ?>
      <ul>
          <li>Candle Holder: $<?php echo tally('Candle Holder'); ?></li>
          <li>Floor Lamp: $<?php echo tally('Floor Lamp'); ?></li>
          <li>Total: $<?php echo $grand_total; ?></li>
      </ul>
      

      在此示例中,您可以看到我在函数内部和外部使用了 $grand_total。他们是无关的。该函数不知道外部 $grand_total 因为它不在其范围内。

      此功能仅用于一件事 - 计算该产品的总数。您可以自行决定每种产品的结果。 您可以编写一个函数来统计所有内容,或者编写一个类来处理所有内容,但这是另一个主题。这个例子只是解释了为什么它没有按照你的要求做

      【讨论】:

      • 您提到了“统计所有功能”。该函数将如何编写?
      • 类似于 Dave 在下面的概述。您必须将其传递给一个数组。这是一种方式。
      【解决方案4】:

      这是由于称为“范围”的编程概念而发生的 当函数的代码运行时,值就是你想要的。

      为了解决问题,首先在函数外部声明变量。

      <?php
      $tax = 0.08;
      $total_price = 0;
      $total_tax = 0;
      $total_shipping = 0;
      $grand_total = 0;
      tally('Candle Holder');
      tally('Coffee Table');
      tally('Floor Lamp');
      ?>
      

      然后在函数 tally() 中,在 if/else 语句之前添加这段代码

      global $tax;
      global $total_price;
      global $total_tax;
      global $total_shipping;
      global $grand_total;
      

      这几乎告诉函数有一个名为“tax”的变量在其当前“范围”之外,并且它应该将其链接到其当前内存。 然后,当函数更新 tax 的值时,它会更新其“范围”之外的主变量,从而保留值 (我举了一个税收的例子,你声明的所有其他变量都是一样的)

      Ps:我知道我可能把你的问题弄错了,如果有,请告诉我,我会更新答案。

      【讨论】:

      • 在这种特殊情况下,全局变量到底有什么问题?
      • 在这种特殊情况下没有任何问题,可能在其他情况下,我发现了。由于这是该计划将要进行的,因此对于这项学校作业,它会起作用。
      猜你喜欢
      • 1970-01-01
      • 2014-03-01
      • 1970-01-01
      • 2020-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-27
      • 2021-08-20
      相关资源
      最近更新 更多