我想将一个 DateTimeZone
对象传递给我的类 Test
中的方法。我有以下代码:
class Test {
function __construct( $timezone_object = new DateTimeZone() ) {
// Do something with the object passed in my function here
}
}
不幸的是,上面的方法不起作用。它给了我一个错误。我知道我可以改为执行以下操作:
class Test {
function __construct( $timezone_object = NULL ) {
if ( $timezone_object == NULL)
$to_be_processed = new DateTimeZone(); // Do something with my variable here
else
$to_be_processed = new DateTimeZone( $timezone_object ); // Do something with the variable here if this one is executed, note that $timezone_object has to be the supported timezone format provided in PHP Manual
}
}
但是,我认为第二个选择似乎不太干净。有没有办法像第一选择一样声明我的方法?
最佳答案
如果你只是在寻找简洁的代码,你可以这样做
class Test {
function __construct( \DateTimeZone $timezone_object = null ) {
$this->ts = $timezone_object ?? new DateTimeZone();
}
}
双??是一个 if null 检查。所以你有类型提示,它只允许 DateTimeZone 或 Null 值(所以这是安全的),然后如果参数为空,你只需分配一个新的 DateTimeZone 实例,否则,使用传入的值。
编辑:找到有关 PHP 7.1+ 的默认 null 的信息
Cannot pass null argument when using type hinting
所以代码可以更深奥,按键次数稍微少一些
class Test {
function __construct( ?\DateTimeZone $timezone_object ) {
$this->ts = $timezone_object ?? new DateTimeZone();
}
}
但在我看来,这太可怕了。
关于php - 在 PHP 中为我的类方法提供默认对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54976411/