How to use strict types with class method overrides in PHP

1 Answer

0 votes
declare(strict_types=1);

class A {
    public function run(int $x): int {
        return $x;
    }
}

class B extends A {
    public function run(int $x): int {   // Must match exactly
        return $x * 2;
    }
}

$b = new B();
echo $b->run(10);     // OK
echo $b->run("10");   // TypeError



/*
run:

ERROR!
20
Fatal error: Uncaught TypeError: B::run(): Argument #1 ($x) must be of type int, string given

*/

 



answered Aug 9 by avibootz
...