如何最好地处理 PHP 中的情况,其中构造函数接收到一个强制性的非空值,该值可能并不总是被初始化?

How to best handle a situation in PHP where constructor receives a mandatory non-null value, which may not always be initialized?

我有一些这样的代码:

class Repository
{
    private $number;

    function __construct(int $number)
    {
        $this->number = $number;
    }

    //example where $number is required
    function readQuote()
    {
        return $this->db->runSql("select * from quote where id = $this->number");
    }
}

我把$number放在构造函数中是因为Repository指的是一个Quote具有特定数字的对象,没有数字就不可能存在Quote。因此,当 Quote 数字已知时,强制数字在那里是有意义的。

不过... 有一种情况是还不知道人数。就像我第一次加载页面时没有定义 (picked/selected) 我想显示的数字,但我希望页面加载和工作。

具体来说,我有这样的代码:

$controller = new Controller(new Repository($number));

//this line does not require Repository, 
//and hence $number can be uninitialized
$controller->generateIndexPage();
...

//this one does, but it is called only when number is already known
$controller->getQuote();

当我知道号码时,一切正常。当它尚未初始化且为 null 时,我的代码因 PHP TypeError 错误而中断(PHP 引擎期望 int,它得到 null).

问题

我该如何处理这种情况?

想法

我能想到的两个解决方案是

像这样在函数参数中给变量一个值:

class Repository{
  private $number;

  function __construct($number = 'x'){
    // Check if the $number is provided and value of $number has changed.
    if(is_numeric($number) && $number != 'x'){numeric
      $this->number = $number;
    }
  }
}

同意亚历克斯对我的问题的评论,我正在考虑采用这种方法:

Controller 可以接受 Repositorynull,因为 Repository 不是我的 Controller 的强制参数。但在 Repository.

上保留 $number 强制性