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

标签 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
    }
}

但是,我认为第二个选择似乎不太干净。有没有办法像第一选择一样声明我的方法?

最佳答案

如果你只是在寻找简洁的代码,你可以这样做

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/

相关文章:

具有子类唯一性和多态性的Java引用类型

python - 如何在 Python 的另一个函数中找出特定函数参数的默认值?

kotlin - 扩展父参数的类默认值

java - 访问同一类中另一个对象的私有(private)字段

php - 如何从子查询中获取唯一计数?

php - 使用 MySQL 或 PHP 获取信息

php - 如何通过检索 'itemname' 列中的项目来创建下拉菜单

java - 如何消除对 Java Bean 的硬依赖

c++ - 如何将使用默认参数的函数传递给 std::thread?

php - 遍历传递给 Twig 模板的所有参数