1

I am New at PHP , so i dont know how to fix it followings are function code,

<?php 

class calculation{

    function add($a,$b){
        echo "Summation= ".($a+$b). "<br/>";
    }
}
Nigel Ren
  • 56,122
  • 11
  • 43
  • 55
Kashem Bhai
  • 11
  • 1
  • 2

2 Answers2

0

probably $a or $b or both are not numbers

You can do something like this:

function add(int $a, int $b){
        echo "Summation= ".($a+$b). "<br/>";
    }

to force the code that uses your function to pass an integer.

You can also do something like this

function add($a,$b){
        echo "Summation= ".((int)$a+(int)$b). "<br/>";
    }

to make a typecast and let Php trying to convert the variables to integers and do the math operation.

It depends on what you exactly need to do.

Carlos
  • 1,411
  • 15
  • 21
0

This means,

When invalid strings are coerced using operators expecting numbers (+ - * / ** % << >> | & ^) or their assignment equivalents. This warning is introduced in PHP 7.1 (http://php.net/manual/en/migration71.other-changes.php).

Check if the parameters are numeric, else throw an exception.

<?php 

class calculation{
    function add($a,$b){
        if(!is_numeric($a) || !is_numeric($b)){
            throw new \Exception("Parameters must be numeric.");
        }

        echo "Summation= ".($a+$b). "<br/>";
    }
}

Fiddle: https://implode.io/DOi100

OR

Make non-numeric values 0.

<?php 

class calculation{
    function add($a,$b){
        $a = is_numeric($a) ? $a : 0;
        $b = is_numeric($b) ? $b : 0;

        echo "Summation= ".($a+$b). "<br/>";
    }
}

Fiddle: https://implode.io/bHerbP

OR

If you want to pass only certain types(Int or Float or Double) of parameters, you can follow @carlos' asnwer

NOTE: Below PHP 7.0, it won't show this warning. Fiddle: https://implode.io/D4yrHO

Ijas Ameenudeen
  • 9,069
  • 3
  • 41
  • 54