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

如何最好地处理PHP中构造函数接收强制非空值的情况,该值可能并不总是初始化的?,php,constructor,initialization,php-7,type-hinting,Php,Constructor,Initialization,Php 7,Type Hinting,我有一些这样的代码: class Repository { private $number; function __construct(int $number) { $this->number = $number; } //example where $number is required function readQuote() { return $this->db->runSql("

我有一些这样的代码:

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
放在构造函数中,因为
存储库
引用了一个具有特定数字的
引用
对象,并且
引用
如果没有该数字就不能存在。因此,当已知编号时,强制该编号存在是有意义的

然而。。。有一种情况是,这个数字还不知道。就像我第一次加载页面时,没有定义(拾取/选择)要显示的数字,但我希望页面能够加载并工作

具体来说,我有如下代码:

$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();
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;
    }
  }
}
当我知道数字时,一切都很顺利。当它尚未初始化且为
null
时,我的代码会因PHP
TypeError
错误而中断(PHP引擎期望
int
,它会得到
null)

问题

我如何处理这种情况

思想

我能想到的两个解决办法是

  • 将$number初始化为
    -1
    ,这将使PHP感到高兴,但它也是一个神奇的值,因此我认为这是不可取的
  • 将我的构造函数改为
    function\uu-construct(int$number=null)
    ,这将消除
    TypeError
    ,但在某种程度上它让我感到厌烦,因为我削弱了构造函数以接受
    null
    ,而不是让它只接受
    int

    • 在函数参数中为变量指定一个值,如下所示:

      $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();
      
      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;
          }
        }
      }
      

      同意Alex对我的问题的评论,我考虑采用这种方法:


      由于Repository不是我的控制器的强制参数,因此,将其设置为
      控制器可以接受
      存储库
      。但是在
      存储库上保持
      $number
      必填项

      如果
      $number
      对于
      存储库
      是必填项,除非您知道编号,否则不要实例化
      存储库
      。谢谢。看起来我的问题是,当出现不需要的情况时,例如对于
      generateIndexPage()
      方法,强制在
      Controller
      上设置一个强制的
      存储库。