如何最好地处理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
时,我的代码会因PHPTypeError
错误而中断(PHP引擎期望int
,它会得到null)
问题
我如何处理这种情况
思想
我能想到的两个解决办法是
- 将$number初始化为
,这将使PHP感到高兴,但它也是一个神奇的值,因此我认为这是不可取的-1
- 将我的构造函数改为
,这将消除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
上设置一个强制的存储库。