strict_types=1必须紧贴

strict_types=1 必须放在文件最顶行
它不是配置项,也不是函数调用,而是一条编译指令,生效前提是:紧贴 <?php 后面,前面不能有任何空格、BOM、注释或 namespace。一旦错位,就等于没写。
- 错误写法:
<?php \n// 注释\ndeclare(strict_types=1);→ 失效 - 错误写法:
<?php \n\ndeclare(strict_types=1);(首行有空格)→ 失效 - 正确写法:
<?php \ndeclare(strict_types=1);→ 严格模式激活 - 用十六进制编辑器或 IDE 的“编码”菜单检查 BOM,UTF-8 with BOM 会导致静默失效
strict_types 只管当前文件里自己写的函数
它不跨文件生效,require 或 include 进来的其他 PHP 文件,哪怕被 strict 文件调用,只要它自己没加 declare(strict_types=1),里面的函数参数照样允许隐式转换。
- A.php 启用了
declare(strict_types=1),定义了function foo(int $x) { ... }→ 调用foo("123")报TypeError - B.php 没声明 strict,定义了
function bar(int $y) { ... }→ 即使 A.phprequire 'B.php'并调用bar("123"),也不会报错 - 要统一约束,就得每个文件都手动加
declare(strict_types=1),不能靠“传染”
传参失败不是因为类型写错了,而是值没过校验
即使函数签名写了 int,传入 "42" 或 42.0 在 strict 模式下依然会炸——PHP 不做任何隐式转换,只认完全匹配的原始类型。
function sum(int $a, int $b): int { return $a + $b; }-
sum(5, 10)✅ -
sum("5", "10")❌ 报Fatal error: Uncaught TypeError -
sum(5.0, 10)❌ 同样报错,float不等于int - 修复方式不是改函数签名,而是调用前显式转换:
sum((int)"5", (int)5.0)
数组查找也得手动开 strict,和 declare 无关
array_search() 默认用松散比较(==),比如搜 "1." 可能命中 "1",这不是 declare(strict_types=1) 能控制的。它只影响函数参数/返回值,不影响内置函数内部逻辑。
- 错误预期:
array_search("1.", $dict)→ 想找键对应值为"1."的项 - 实际行为:默认松散比较,
"1." == "1"为 true,返回第一个匹配键(如"I") - 正确做法:第三个参数设为
true,启用严格比较:array_search("1.", $dict, true) - 这个
true和declare(strict_types=1)完全无关,别混淆
php免费学习视频:立即使用
踏上前端学习之旅,开启通往精通之路!从前端基础到项目实战,循序渐进,一步一个脚印,迈向巅峰!











