如何总结成分的数组?

时间:2016-11-16 06:40:09

标签: php for-loop

我正在尝试使用forloop实现getCost()函数,但我是php新手并且无法理解如何实现。我只是不断收到错误说未定义的变量。  这是我的代码

<?php 
class Burger {     
public $title = '';
private $ingredients = array(); 

    public function __construct($n) { 
        $this->name = $n; 
    } 

    public function addIngredient($ing) { 
        array_push($this->ingredients, $ing); 
    } 

    public function getCost() { 
        foreach( $ingredients as $ingredient=> $costDollars){
               $price += $costDollars;

                return $price;
 }
    } } 

class Ingredient {     
public $name = 'Ingredient';     public $costDollars = 0.0; 

public function __construct($n, $c) { 
    $this->name = $n; 
    $this->costDollars = $c; 
  } } 

$myBurger = new Burger('Tasty Burger'); 
$myBurger->addIngredient(new Ingredient('Meat', 0.3)); 
$myBurger->addIngredient(new Ingredient('Cheese', 0.2)); 
$myBurger->addIngredient(new Ingredient('Beetroot', 0.2)); 
$myBurger->addIngredient(new Ingredient('Pineapple', 0.4)); 

echo $myBurger->getCost(); ?> 

2 个答案:

答案 0 :(得分:2)

当您尝试访问类属性$this时,您忘记了$ingredients

public function getCost() {
    $price = 0;
    foreach( $this->ingredients as $ingredient){
        $price += $ingredient->costDollars;
    }
    return $price;
}

正如您在上面的代码中看到的那样,return - 语句也会在循环之后移动。如果循环中有return,则在第一次迭代后返回变量。

答案 1 :(得分:1)

<?php
class Burger {
public $title = '';
private $ingredients = array();

public function __construct($n) {
  $this->name = $n;
}

public function addIngredient($ing, $cost) {
   $this->ingredients += array($ing => $cost); // Wont overide! EXTRA CHEEZ PLZ
}

public function getCost() {
//forloop
   $totalprice = 0;  // Start Register Cha Ching!
   foreach($this->ingredients as $ing => $price){ // Add Items (*scanner Beeps*
      $totalprice += $price;
   } // All Done with items, let return cost
   return $totalprice; // Return Value to Function Call
}
}


$myBurger = new Burger('Tasty Burger');
$myBurger->addIngredient('Meat', 0.3);
$myBurger->addIngredient('Cheese', 0.2);
$myBurger->addIngredient('Beetroot', 0.2);
$myBurger->addIngredient('Pineapple', 0.4);

   echo $myBurger->getCost(); ?> // ECHO Value to Function Call