PHP 7 Bool类型提示不起作用

时间:2017-09-26 14:24:17

标签: php oop type-hinting

我有点难以接受标量类型提示问题(PHP7应该能够处理)。基本上,我创建一个bool类型提示的方法只允许传递布尔值。然而它失败了,并让其他类型的字符串传递。我相信过去这对我有用。以该片段为例。第一个转储导致false(这是有意义的,因为'test'是一个字符串),第二个转储导致true这对我没有意义。我希望触发PHP错误,因为该类型不是布尔值。有什么想法吗?

<?php
class Test{
    function something(bool $test){
       var_dump($test); // "Second dump"
    }
}

$value = 'test';
var_dump(is_bool($value)); // "First dump"
$test = new Test;
$test->something($value);

结果:

bool(false) 
bool(true)

3 个答案:

答案 0 :(得分:3)

您必须在文件中声明严格输入 [1],以强制PHP不执行类型强制 [2]。

[1] - http://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration.strict

[2] - &#34;默认情况下,如果可能,PHP会将错误类型的值强制转换为预期的标量类型。&#34;

php <?php declare(strict_types=1);

答案 1 :(得分:1)

问题在于PHP具有基元的自动转换。可能出于哲学原因,他们长期没有改变这一点。这就是PHP中禁止以前原始类型提示的原因:https://bugs.php.net/bug.php?id=29508

由于PHP具有自动转换功能,您应该这样做以确保:

class Test{
    function something($test){
       if(!is_bool($test)) {
            throw new InvalidArgumentException("Boolean expected.");
       }
    }
}

编辑:阅读以下有关PHP 7 https://www.phpclasses.org/blog/post/269-PHP-7-Scalar-Type-Hinting-Finally-Approved.html

中标量类型提示的文章

在PHP 7中,最终可以通过添加

来创建包含基元类型检查工作的代码
declare(strict_types=1); 

在文件的开头。

答案 2 :(得分:1)

您正在寻找的神奇功能就是这个。把它放在你班上面的第一行!

declare(strict_types=1) ;

现在你的代码看起来像这样:

<?php
declare(strict_types=1) ;

class Test{
    function something(bool $test){
       var_dump($test); // "Second dump"
    }
}

$value = 'test';
var_dump(is_bool($value)); // "First dump"
$test = new Test;
$test->something($value);

现在它会抛出一个错误! http://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration.strict

在此处查看:https://3v4l.org/eLS1T

最后一点,您需要在每个文件

上设置此项
相关问题