You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为Period类属性赋值DateTimeImmutable时触发对象转字符串错误,如何解决?

问题:PHPUnit测试中DateTimeImmutable无法转字符串错误

我在用PHPUnit为Web API编写单元测试,其中需要测试的Period类用于存储必填的开始日期(DateTimeImmutable类型)与可选的结束日期(?DateTimeImmutable类型),且要求开始日期不得晚于结束日期。编写完Period类与对应的单元测试后,运行测试时触发错误:Object of class DateTimeImmutable could not be converted to string,错误定位到Period类构造函数的属性赋值行,找不到匹配的解决方案,特此求助。

Period类代码

use DateTimeImmutable;

final class Period
{
    private DateTimeImmutable $startDate;

    private ?DateTimeImmutable $endDate;

    public function __construct(
        DateTimeImmutable $startDate,
        ?DateTimeImmutable $endDate,
    ) {
        $this->validateDates($startDate, $endDate);
        $this->$startDate = $startDate;
        $this->$endDate = $endDate;
    }

    /* Other stuff here*/

    private function validateDates(
        DateTimeImmutable $start,
        ?DateTimeImmutable $end
    ): void {
        if (!is_null($end) && $start > $end) {
            throw new InvalidArgumentException(
                'Start Date cannot be later than End Date',
                422
            );
        }
    }
}

单元测试代码

use DateTimeImmutable;

final class PeriodTest extends TestCase
{
    /** @test */
    public function shouldInstantiateNewObject(): void
    {
        $startDate = new DateTimeImmutable('2023-12-20');
        $endDate = new DateTimeImmutable('2023-12-21');

        $period = new Period($startDate, $endDate);

        self::assertSame($startDate, $period->getStartDate());
        self::assertSame($endDate, $period->getEndDate());
    }
}

错误信息

There was 1 error:

1) tests\Unit\Domain\ValueObjects\PeriodTest::shouldInstantiateNewObject
Error: Object of class DateTimeImmutable could not be converted to string

/home/jb3/autodoc/doc-api/src/Domain/ValueObjects/Period.php:28
/home/jb3/autodoc/doc-api/tests/Unit/Domain/ValueObjects/PeriodTest.php:22

问题原因与解决办法

错误根源在构造函数的属性赋值语句:

$this->$startDate = $startDate;
$this->$endDate = $endDate;

这里使用了PHP的变量属性语法,它会尝试将$startDate这个DateTimeImmutable对象转换为字符串,以此作为属性名来访问类成员,但DateTimeImmutable对象无法直接转换为字符串,因此触发错误。

正确的写法是直接引用类的属性名,不需要额外的$符号:

$this->startDate = $startDate;
$this->endDate = $endDate;

修改构造函数后重新运行测试,即可解决该问题。

内容的提问来源于stack exchange,提问作者JB3

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.03 13:20:27