- round: documentation ( source)
- strtoupper: documentation ( source)
- array_walk: documentation ( source)
- constant: documentation ( source)
<?php
// Un panier d'achat simple, qui contient une liste de produits
// choisis et la quantité désirée de chaque produit. Il inclut
// une méthode qui calcule le prix total des éléments dans le panier
// en utilisant une fonction de rappel anonyme.
class Panier
{
const PRICE_BEURRE = 1.00;
const PRICE_LAIT = 3.00;
const PRICE_OEUF = 6.95;
protected $products = array();
public function add($product, $quantity)
{
$this->products[$product] = $quantity;
}
public function getQuantity($product)
{
return isset($this->products[$product]) ? $this->products[$product] :
FALSE;
}
public function getTotal($tax)
{
$total = 0.00;
$callback =
function ($quantity, $product) use ($tax, &$total)
{
$pricePerItem = constant(__CLASS__ . "::PRICE_" .
strtoupper($product));
$total += ($pricePerItem * $quantity) * ($tax + 1.0);
};
array_walk($this->products, $callback);
return round($total, 2);
}
}
$mon_panier = new Panier;
// Ajout d'élément au panier
$mon_panier->add('beurre', 1);
$mon_panier->add('lait', 3);
$mon_panier->add('oeuf', 6);
// Affichage du prix avec 5.5% de TVA
print $mon_panier->getTotal(0.055) . "\n";