我有这段代码:
<?php
declare(strict_types=1);
# test_1 with bool
function test_1(bool $bool) {
return $bool ? 'Yes' : 'No';
}
# test_2 with boolean
function test_2(boolean $bool) {
return $bool ? 'Yes' : 'No';
}
$value = false;
# Why does this work ...
echo test_1($value) . "<br>";
# ... but this doesn't?
echo test_2($value) . "<br>";
?>
严格类型似乎适用于bool,但不适用于布尔值。
php.net says:
不支持上述标量类型的别名。相反,它们被视为类或接口名称。例如,使用boolean作为参数或返回类型将需要一个参数或返回值,该值是类或接口boolean的实例,而不是bool类型
但不知怎的,我不明白。有人可以向我解释一下吗?
答案 0 :(得分:1)
PHP不允许您使用 boolean 作为类型定义,因为关键字是 bool 。如果键入 boolean ,它会将其解释为对类名的调用。有什么难以理解的?
答案 1 :(得分:1)
PHP仅支持int
,float
,bool
,string
和array
类型。任何不同的返回类型(如boolean
)引用类名。
<?php declare(strict_types=1)
class boolean {}
func testReturnBoolean(): boolean {
// this function should return instance of
// class "boolean", not bool type (true/false)
}
func testReturnBool(): bool {
// this function should return true or false,
// otherwise it throws an exception
}
func testReturnBoolOrNull():? bool {
// this function should return true, false or null
// otherwise it throws an exception
// syntax :? string works since php 7.1
}