Last Updated: February 25, 2016
·
256
· florenceokosun

Simple addition

Here's a small PHP code snippet to dynamically add an array of numbers the OO way

let's say we have a Math.php class:

class Math {

    public static function add(...$nums) {
              return array_sum($nums);
      }
{

Then say you have a index.php file, drop this in:

Math::add(1,2,3,4,5,6,7,8,9);

Here, you are simply accessing the static method add from the Math Class. This will output:

45

If you are using a recent version of PHP, take note of the param in the add method (...$nums) but if you are not using a recent version then you may do this:

public static function add(){
       return array_sum(func_get_args());
}