【发布时间】:2019-04-21 22:02:20
【问题描述】:
我今天使用 PHP(至少 7.1 和 7.2)遇到了这个问题,代码如下:
namespace PlaceHolderX\Tests\PHPUnit\Unit;
use PHPUnit\Framework\TestCase;
final class BreakingClassesTest extends TestCase
{
public function testBreak(): void
{
$tester = new SomeClassA();
$tester->test();
$this->assertNull($tester->get());
}
}
interface InterfaceA {
public function test(string $testString): void;
}
class SomeClassA implements InterfaceA
{
/** @var null|string */
private $testString;
public function test(string $testString = null): void
{
$this->testString = $testString;
}
public function get(): ?string
{
return $this->testString;
}
}
所以我有一个接口 (InterfaceA),它有一个需要字符串的方法。此参数不可为空,因为如果我想将其指定为:
public function test(?string $testString): void;
但是在实现类 (SomeClassA) 中,我可以使用默认值 null 覆盖参数定义,这会导致我的接口不打算出现的行为。
所以我的主要问题是:为什么会这样?当然,我们需要在代码审查中检查这一点,但很容易错过。
我尝试搜索导致此行为的原因,但无法找到解释。也许我的搜索条件已关闭。
【问题讨论】:
标签: php type-hinting