MrKeyboard MrKeyboard - 24 days ago 7
PHP Question

How to sum the array of ingredient?

I am trying to implement the

getCost()
function using a forloop but i am new to php and having trouble with understanding how to implement. i just keep getting error saying undefined variable.
Here is my code

<?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(); ?>

Answer

You're forgetting $this when you're trying to access the class property $ingredients:

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

As you can see in the above code, the return-statement is also moved after the loop. If you have the return in your loop, the variable will be returned after the first iteration.