Guest User

Untitled

a guest
Feb 23rd, 2018
93
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.15 KB | None | 0 0
  1. <?php
  2.  
  3. /*
  4. * Before PHP 5.6.0
  5. */
  6. function sum()
  7. {
  8. $result = 0;
  9.  
  10. foreach (func_get_args() as $i) {
  11. $result += $i; // assumption that $i is always an integer
  12. }
  13.  
  14. return $result;
  15. }
  16.  
  17. // Examplary call of sum()
  18. echo sum(); // returns 0
  19. echo sum(1, 2); // returns 3
  20. echo sum(4, 4, 5, 7); // returns 20
  21.  
  22. /*
  23. * PHP 5.6.0 or later
  24. */
  25. function sum(...$values) {
  26. $result = 0;
  27.  
  28. foreach ($values as $i) {
  29. $result += $i; // assumption that $i is always an integer
  30. }
  31.  
  32. return $result;
  33. }
  34.  
  35. /*
  36. * PHP 5.6.0 or later including type hinting
  37. */
  38. class IntObject
  39. {
  40. private $value;
  41.  
  42. public function __construct($value) {
  43. $this->value = $value;
  44. }
  45.  
  46. public function getValue() {
  47. return $this->value;
  48. }
  49.  
  50. }
  51.  
  52. function sum(IntObject ...$values) {
  53. $result = 0;
  54.  
  55. /** @var $i IntObject */
  56. foreach ($values as $i) {
  57. // getValue() can be called without any issues, since PHP already checked that all values in $values are of the type IntObject
  58. $result += $i->getValue();
  59. }
  60.  
  61. return $result;
  62. }
  63.  
  64. // Examplary call of sum()
  65. var_dump(sum(new IntObject(1), new IntObject(2), new IntObject(3)));
Add Comment
Please, Sign In to add comment