问题描述
我使用的是 PHP 8.0,但由于某些原因,联合类型和可为空类型似乎无法根据文档工作。 ?Type 或 Type|null 应根据文档 (https://www.php.net/manual/en/language.types.declarations.php#language.types.declarations.union)
将参数设为可选8.0.0
PHP Fatal error: Uncaught ArgumentCountError: Too few arguments to function test(),1 passed in /var/www/test/test.PHP on line 10 and exactly 2 expected in /var/www/test/test.PHP:4
Stack trace:
#0 /var/www/test/test.PHP(10): test()
#1 {main}
thrown in /var/www/test/test.PHP on line 4
简单的测试代码
//function test(string $hello,?string $world) {
function test(string $hello,string|null $world) {
return $hello . ' ' . ($world ?? 'world');
}
echo PHPversion() . PHP_EOL;
// Outputs 8.0.0
echo test('hello') . PHP_EOL;
// Expected output: hello world
echo test('hola','mundo');
// Expected output: hola mundo
这里出了什么问题?
解决方法
在 PHP 8 中使用 string|null
作为类型提示并不意味着参数是可选的,只是它可以为空。这意味着您可以将 null 作为值(或字符串,显然)传递,但参数仍然是必需的。
如果你想让一个参数成为可选,你需要提供一个默认值,如下:
function test(string $hello,string|null $world = null) {
// ...
}
在早期版本的 PHP 中也是如此,使用 ?string
语法;参数仍然是必需的,但 null 是一个有效值。