首页 > 解决方案 > 如何在不触发错误 PHP 的情况下将可选参数和数据类型传递给方法

问题描述

我正在尝试将日期值传递给我的存储库文件中的一个方法,以用作查询我的数据库的选项。

我正在做一个 Symfony 项目。

基本上,我目前正在尝试的是在我的控制器中

// send my dates to repository
    $result = $entityManager->getRepository(Repository1::class)->getData($start, $end);

然后在我的存储库中,我尝试在我的 getData 方法中接收它

/**
     * @param bool|null $data
     * @param string|null $start
     * @param string|null $end
     * @return MountPort[]
     */


    public function getData(bool $data = null,$start = null, $end = null)
    {
//trying to collect dates here to work with

}

但后来我不断收到这个错误

Repository1::getData() must be of the type bool or null, object given, called in.

请问我该怎么做才能使我的日期通过而不会触发 bool 数据类型错误

请问字符串是日期的正确数据类型还是我也做错了?

请注意,我也尝试过像这样传递字符串数据类型,但这并没有成功

public function getData(bool|string $data = null,$start = null, $end = null)
        {

我得到的错误

syntax error, unexpected '|', expecting variable (T_VARIABLE)

标签: phpsymfony

解决方案


就像 dbrumann 说的,在你的例子中,你不使用 $data 所以我假设你不需要它,你只需要在你的控制器中将它定义为 null 并将 bool 保留在你的函数参数中。

$result = $entityManager->getRepository(Repository1::class)->getData(null, $start, $end);

public function getData(bool $data = null, $start = null, $end = null)
{}

推荐阅读