dstnlhhv791576 2017-10-07 14: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 15: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.

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

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?