【问题标题】:PHP 7: use both strict and non-strict type hinting?PHP 7:同时使用严格和非严格类型提示?
【发布时间】:2015-12-08 21:05:12
【问题描述】:

所以 PHP 7 现在有标量类型提示(w00t!),您可以根据 PHP 中的设置将类型提示设置为严格或非严格。 Laracasts 使用定义 IIRC 进行设置。

有没有办法在一个文件(如数学库)中对标量进行严格类型提示,同时在其他地方使用非严格类型,而无需随意更改代码中的设置?

我想通过不烦躁语言设置来避免引入错误,但我喜欢这个想法。

【问题讨论】:

  • PS - 我不允许任何人更改语言设置以实现可移植性,并且在执行过程中更改它们会受到流放的惩罚。

标签: php-7


【解决方案1】:

确实,您可以随心所欲地混合搭配,事实上,该功能就是专门为这种方式设计的。

declare(strict_types=1); 不是语言设置或配置选项,它是一个特殊的每个文件声明,有点像namespace ...;。它只适用于你使用它的文件,不会影响其他文件。

所以,例如:

<?php // math.php

declare(strict_types=1); // strict typing

function add(float $a, float $b): float {
    return $a + $b;
}

// this file uses strict typing, so this won't work:
add("1", "2");

<?php // some_other_file.php

// note the absence of a strict typing declaration

require_once "math.php";

// this file uses weak typing, so this _does_ work:
add("1", "2");

返回输入的工作方式相同。 declare(strict_types=1); 适用于文件中的函数调用(非声明)和return 语句。如果您没有declare(strict_types=1); 语句,则该文件使用“弱类型”模式。

【讨论】:

  • 当人们在我的库中调用方法时,我无法强制执行严格的输入,这让我很失望。也许是 7.1 的一个功能? :)
  • @DerrekBertrand 如果你真的想,你可以做类似&lt;?php declare(strict_types=1); function myPublicFunc(...$args) { return _myPublicFunc(...$args); } function _myPublicFunc(int $foo, string $bar) { /* actual function here */ }
  • 如果不让你的调用堆栈更脏或不使用像这样的黑魔法就无法做到这一点,我更难过。不过好戏!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-24
  • 1970-01-01
  • 2012-05-03
  • 2011-03-09
  • 2012-11-12
  • 2014-01-02
  • 2019-02-09
相关资源
最近更新 更多