PHP7 - 类型提示可信吗?

标签 php php-7 scalar

我最近开始研究 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.

Returning values

关于PHP7 - 类型提示可信吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37171492/

相关文章:

php - 如何用自定义 .ini 文件覆盖一些 PHP 配置默认值?

PHP OOP 与 Javascript

php - 将 PHP 7 与 WAMP 结合使用

php - "Empty delimiter"使用PHP explode()函数时出现警告

sql-server-2008 - 如何在sql server 2008中创建和调用标量函数

python - 使用条件语句从 pandas df 列中减去标量给出 ValueError : The truth value of a Series is ambiguous

PHP Base64 编码 JSON 斜线问题

java - 如何用 Apache Derby 代替 MySQL Server 作为 PHP 应用数据库?

codeigniter - 使用 PHP7 在 Codeigniter 中进行 session

Python - 将 for 循环变成单行代码