我最近开始研究 PHP 7 中引入的新类型提示,发现它是一个非常好的和有用的补充,可以添加到我的一些应用程序中,因此我已经这样做了,但是我有一个问题关于参数和返回类型提示。
假设我有一个基本函数,它对两个参数执行数学运算并返回一个整数。
function addTwo(int $a, int $b): int {
return $a + $b;
}
预期的参数应该是整数,我们希望从函数中收到一个整数值,但是这总是有保证的,还是应该在函数内进行进一步的验证,例如 is_int 以确保两个参数都是整数?
最佳答案
这取决于条件。例如,在你的例子中传递lines不会成功,但是传递float - 没有问题,它会默默地转换为int。
你必须写declare(strict_types=1);
strict_types=1 只能应用于直接在第一行声明它的文件,没有办法解决这个问题。
Strict typing also has an effect on return type declarations. In the default weak mode, returned values will be coerced to the correct type if they are not already of that type. In strong mode, the returned value must be of the correct type, otherwise a TypeError will be thrown.
关于PHP7 - 类型提示可信吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37171492/