Last Updated: February 25, 2016
·
473
· 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());
}

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

PHP applications still send a browser full of JavaScript. Hardening the server does not inventory the payment, analytics, and plugin scripts that run after the HTML is delivered.

Security insights from Cside