How to use strict types with interfaces in PHP

1 Answer

0 votes
declare(strict_types=1);

interface MathOp {
    public function compute(int $x, int $y): int;
}

class Add implements MathOp {
    public function compute(int $x, int $y): int {
        return $x + $y;
    }
}

$op = new Add();
echo $op->compute(2, 3);     // OK
echo $op->compute("2", 3);   // TypeError


/*
run:

RROR!
5
Fatal error: Uncaught TypeError: Add::compute(): Argument #1 ($x) must be of type int, string given

*/

 



answered Aug 9 by avibootz
...