【问题标题】:Giving a default object to my class method in PHP在 PHP 中为我的类方法提供默认对象
【发布时间】:2019-07-25 08:41:44
【问题描述】:

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

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

【问题讨论】:

  • @LawrenceCherone - 这不起作用,因为如果传入 null,类型提示将引发异常。您可以执行 \DateTimeZone $timezone_object = null - 给它一个 null 默认值将允许它,但是解决方案并没有真正帮助他。
  • 不可能将对象创建为函数定义的一部分。您只允许在编译时使用被视为常量的东西(或可以用作常量的东西)(当 PHP 的东西 jiggy 解析和编译定义时){不能拼写解释器}
  • 基本上在解析函数和方法的时候,PHP 并不知道所有的类,所以它根本无法使用它们。或者类似的东西,我相信对此有更多的“技术”解释,但这是它的基本要点。正如其他指出的那样,首选方法是输入提示参数,默认情况下将其设置为 null 并在方法中检查并将其设置在那里。或者只是不设置默认值并始终传递它。我个人会做#2
  • @LawrenceCherone - 我只是按照他在问题中输入的代码进行 - 他专门检查 null。因此,它似乎是一个用例。如果他传递了其他东西,他应该将它包装在一个 try/catch 块中并寻找它。处理这个问题不是类的责任,而是调用代码的责任。

标签: php oop default-parameters


【解决方案1】:

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

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

但在我看来,这太可怕了。

【讨论】:

  • 哦还有一件事,为什么第二个在你看来很可怕?是不是因为可读性差?
  • @RichardW - 根据我的经验,有时少即是多。这 ??已经够糟糕了,更不用说要求知识知道了?在类型提示之前意味着您允许空值。在我看来,代码对读者来说应该是立即直观的。如果您不知道 ?\DateTimeZone 是做什么的,您需要花 10-15 分钟让您的谷歌搜索正确地弄清楚。就是它 ”?”每个不知道语法的开发人员都值 20 美元?时间=金钱
  • 我明白了,感谢您分享您的经验。像这样的轶事笔记肯定会帮助我成为一个更好的程序员。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-04-12
  • 1970-01-01
  • 1970-01-01
  • 2012-08-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多