ntzm/
为超级防御性PHP提供严格类型转换
1.2.0
2019-06-22 11:06 UTC
Requires (Dev)
- phpunit/phpunit: ^8.2
This package is auto-updated.
Last update: 2024-09-29 05:21:56 UTC
README
为超级防御性PHP提供严格类型转换
安装
$ composer require ntzm/strict-casts
用法
本包提供以下严格类型转换
stringToBoolintToBoolstringToIntstringToFloat
以及以下通用转换,这些转换可以与任何输入一起使用,但在可能的情况下使用严格转换
toBooltoInttoFloat
所有提到的函数都位于StrictCasts命名空间下。因此,在使用之前,必须通过use function语句导入。
为什么?
PHP的内置类型转换一点也不严格,几乎可以接受任何类型并将其转换为另一种类型,无论转换是否有效,例如
(int) 'hello' === 0; (int) '5 hello' === 5; (int) 'hello 5' === 0; (int) '123,456' === 123;
这是大量错误、头痛和哭泣的来源。
通过在转换之前确保转换的有效性,我们可以确保转换恰好如我们所期望的那样发生,或者它会失败!例如
use function StrictCasts\stringToInt; stringToInt('123') === 123; stringToInt('-123') === -123; stringToInt('hello'); // throws exception stringToInt('5 hello'); // throws exception stringToInt('hello 5'); // throws exception stringToInt('123,456'); // throws exception