【发布时间】: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