How to use strict types with nullable types in PHP

1 Answer

0 votes
declare(strict_types=1);

function greet(?string $name): string {
    return $name ? "Hello, $name" : "Hello, guest";
}

echo greet(null) . "\n";     // OK
echo greet("Galaxy") . "\n"; // OK
echo greet(738);      // TypeError


/*
run:

ERROR!
Hello, guest
Hello, Galaxy

Fatal error: Uncaught TypeError: greet(): Argument #1 ($name) must be of type ?string, int given

*/

 



answered Aug 9 by avibootz
...