简体   繁体   中英

strict_types doesn't work when included

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM