dstnlhhv791576 2017-10-07 06:31
浏览 111
已采纳

strict_types在包含时不起作用

I have a method that returns true or false, however when I add a type declaration isAdmin() : string it is not throwing a fatal error.

I have declare(strict_types=1); in a second file that is included before the class. Example:

file1.php

<?php
declare(strict_types=1);

file2.php

<?php
include "file1.php";

class Test
{    
    public function user() : int
    {
        return true;   
    }
}

$test = new Test();
var_dump($test->user());

This code won't throw a fatal error. Instead the var_dump returns the bool as int(1). If I change method type to a string, var_dump returns the bool as string(1) "1".

How can I avoid putting declare(strict_types=1); in every model file?

  • 写回答

1条回答 默认 最新

  • dto52236 2017-10-07 07:06
    关注

    It is not currently possible to globally declare strict typing in PHP. From the manual:

    It is possible to enable strict mode on a per-file basis

    And

    Strict typing applies to function calls made from within the file with strict typing enabled, not to the functions declared within that file. If a file without strict typing enabled makes a call to a function that was defined in a file with strict typing, the caller's preference (weak typing) will be respected, and the value will be coerced.

    My guess is that, in part, this was to maintain compatibility amongst packages. What if you enable if globally and some package you're using requires strict typing to be off?

    Until further notice you'll have to declare it in every file you're going to be using it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

悬赏问题

  • ¥100 冷钱包突然失效,急寻解决方案
  • ¥15 下载honeyd时报错 configure: error: you need to instal a more recent version of libdnet
  • ¥15 距离软磁铁一定距离的磁感应强度大小怎么求
  • ¥15 霍尔传感器hmc5883l的xyz轴输出和该点的磁感应强度大小的关系是什么
  • ¥15 vscode开发micropython,import模块出现异常
  • ¥20 Excel数据自动录入表单并提交
  • ¥30 silcavo仿真,30分钟,只需要代码
  • ¥15 FastReport 怎么实现打印后马上关闭打印预览窗口
  • ¥15 利用3支股票数据估计其均值和方差的95%置信区间。
  • ¥15 微信小程序运行一项功能时,弹出未知错误弹框,检查代码没有问题
手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部