在PHP中为我的类方法提供默认对象

时间:2019-03-04 03:56:12

标签: php oop default-parameters

我想将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
    }
}

但是,我认为第二种选择似乎很不干净。有没有办法像首选方法那样声明我的方法?

1 个答案:

答案 0 :(得分:3)

如果您只是在寻找简洁的代码,则可以

class Test {
    function __construct( \DateTimeZone $timezone_object = null ) {
        $this->ts = $timezone_object ?? new DateTimeZone();
    }
}

双重??是一个如果为null的检查。因此,您具有类型提示,将仅允许输入DateTimeZone或Null值(这样是安全的),然后,如果参数为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();
    }
}

但是我认为这太可怕了。