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

时间:2013-10-30 17:17:49

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

尝试学习在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.如果我尝试将原始值变量放在函数之外,浏览器将返回错误: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 个答案:

答案 0 :(得分:2)

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

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

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

答案 1 :(得分:2)

其他人所说的问题是范围。在您使用代码的情况下,可能使用静态var(不是首选),将true传递给第二个arg以将$ 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 :(得分:1)

<?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 :(得分:0)

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

为了解决这个问题,首先要将变量OUTSIDE声明为函数。

<?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的值时,它会更新其“scope”之外的主变量,从而保留值 (我给出了一个税收的例子,对于你声明为全局的每个其他变量都是一样的)

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