函数外部/内部的变量:PHP 初学者


variables outside/inside of a function: PHP beginner

尝试学习如何在 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_总计中。我知道这是因为该函数贯穿开头(顶部)并将 $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>

完全按照我想要的去做!感谢您的帮助! 我知道数组可以帮助解决这个问题,但我现在才在我的课程中谈到这一点。

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

在您的情况下,您希望一个函数 - 一个独立的进程 - 作为一个持续运行的程序工作......或类似的东西。也许你需要做的是重新考虑你对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,因为它不在其范围内。

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

正如其他人所说,问题是范围。 在您拥有的代码的情况下,也许使用静态变量(不是首选),将 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'];
}
<?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];
?>

像这样的东西

这是由于称为"scope"的编程概念而发生的当函数的代码运行时,值正是您想要的。

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

<?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:我知道我可能弄错了你的问题,如果是这样,请告诉我,我会更新答案。