Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /*
- * Before PHP 5.6.0
- */
- function sum()
- {
- $result = 0;
- foreach (func_get_args() as $i) {
- $result += $i; // assumption that $i is always an integer
- }
- return $result;
- }
- // Examplary call of sum()
- echo sum(); // returns 0
- echo sum(1, 2); // returns 3
- echo sum(4, 4, 5, 7); // returns 20
- /*
- * PHP 5.6.0 or later
- */
- function sum(...$values) {
- $result = 0;
- foreach ($values as $i) {
- $result += $i; // assumption that $i is always an integer
- }
- return $result;
- }
- /*
- * PHP 5.6.0 or later including type hinting
- */
- class IntObject
- {
- private $value;
- public function __construct($value) {
- $this->value = $value;
- }
- public function getValue() {
- return $this->value;
- }
- }
- function sum(IntObject ...$values) {
- $result = 0;
- /** @var $i IntObject */
- foreach ($values as $i) {
- // getValue() can be called without any issues, since PHP already checked that all values in $values are of the type IntObject
- $result += $i->getValue();
- }
- return $result;
- }
- // Examplary call of sum()
- var_dump(sum(new IntObject(1), new IntObject(2), new IntObject(3)));
Add Comment
Please, Sign In to add comment