Guest User

Untitled

a guest
Jun 21st, 2018
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.86 KB | None | 0 0
  1. <?php
  2. // Declare a basic shopping card that allows us to
  3. // add products to it, with a member that allows us
  4. // to get the quantity of a product we have added using
  5. // a callback function
  6. class Card
  7. {
  8. public static $products = Array();
  9.  
  10.  
  11. public static function add($product, $quantity)
  12. {
  13. self::$products[$product] = $quantity;
  14. }
  15.  
  16. public static function getQuantity($product)
  17. {
  18. $quantity = false;
  19.  
  20. array_map(function($value, $key) use($product, &$quantity)
  21. {
  22. if($key == $product)
  23. {
  24. $quantity = $value;
  25. }
  26.  
  27. },
  28. array_values(self::$products),
  29. array_keys(self::$products)
  30. );
  31.  
  32. return($quantity);
  33. }
  34. }
  35.  
  36. // Add some items to our card
  37. Card::add('Butter', 1);
  38. Card::add('Milk', 3);
  39. Card::add('Eggs', 6);
  40.  
  41. // Now get the total 'Eggs' we added
  42. printf('The card contains %d eggs', Card::getQuantity('Eggs'));
  43. ?>
Add Comment
Please, Sign In to add comment