我有以下代码:
<?php
class test{
//here we get the total price for the amount, and print-it on screen
public function priceProd($amount){
if (!empty($amount)) {
$price = 5;
}
//getting the sum and outputed using echo
$sum = $price * $amount;
echo $sum.'<br>';
//building the array
$answer = array();
$answer['sum'] = $sum;
}
//here we get the total price for all the values outputed by the priceProd function
public function sumProd(){
}
//closing the class
}
$test = new test;
//feeding amount values to function and getting multiple sums
echo $test->priceProd(2);
echo $test->priceProd(4);
//getting all the total of sums
echo $test->sumProd();
?>
如何使函数sumProd成为函数priceProd的所有输出的总和。现在,即使函数的示例未完成,它似乎只接受并输出$ sum的最后一个值。如果我使用数据库来存储所有值,我认为更简单,但是使用这样的原始输出,我不知道如何找到答案。
欢迎任何类型的答案。非常感谢你!
答案 0 :(得分:2)
你应该使用array
作为函数的返回值..
等。
$answer = array();
$answer['sum'] = $sum;
$answer['price'] = $price;
$answer['product'] = $product;
return $answer;
答案 1 :(得分:0)
让我澄清一些事情:
1)。你不能在一个函数中返回两次。 (见下面的产品功能)
A)。打印按金额*价格计算的小计的一项功能 - B)。打印总费用的另一个功能。
这将有效:
班级考试{
private $total = array();
public function product($product, $amount){
echo $amount.' - '.$product.' - ';
$this->amount = $amount;
$this->product = $product;
return; // if you need this to return a value, put it here.
}
public function priceProd($product){
$amount = $this->amount;
if ($product == 'pen') {
$price = 10;
} elseif ($product == 'gum') {
$price = 5;
}
$sum = $price * $amount;
$this->total = $this->total + $sum;
return $this->price = $sum.'<br>';
}
public function sumProd(){
return $this->total;
// or, from the looks of the rest, you probably want to:
echo "Total: ".$this->total;
}
}