在静态方法内部调用构造函数是个好主意吗?
比方说,我有一个本地化的日期类,其中正常用法是创建一个对象。
$d = new Date(mktime(), 'MM-DD-YYYY', array('locale' => 'es'));
现在,如果我不想总是显式创建一个新对象,而是想要更多类似的东西,该怎么办?
<p>The date is <?php echo
Date::formatDate( mktime(), 'MM-DD-YYYY', array('locale'=>'es') );?>
</p>
在我的 formatDate
方法中,调用构造函数在内部创建日期对象,或者我应该完全使所有内部方法调用静态?
class Date {
function getLocalisedDate( $time, $format, $options ) {
$obj = Date::Date(
$time, $format, $options
); // invoke the constructor
return $obj->get();
}
};
我还没有开发很多类,我想知道这是否是 OO 语言中的常见模式。
Let's say for example I had a localised date class where the normal usage was to create an object.
$d = new Date(mktime(), 'MM-DD-YYYY', array('locale' => 'es'));
Now, what if I didn't want to always create a new object explicitly, but instead wanted something more along the lines of...
<p>The date is <?php echo
Date::formatDate( mktime(), 'MM-DD-YYYY', array('locale'=>'es') );?>
</p>
In my formatDate
method, would it be a good idea to invoke the constructor to internally create a date object, or should I completely make all internal method calls static?
class Date {
function getLocalisedDate( $time, $format, $options ) {
$obj = Date::Date(
$time, $format, $options
); // invoke the constructor
return $obj->get();
}
};
I haven't developed many classes, I'm wondering if it's a common pattern in OO languages.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题出在< php 5.3 静态方法总是会创建硬编码类的实例。因此,如果您实际上使用扩展了
Date
的MyAdvancedDate
,您总是会获得父级的实例,因为self
和__CLASS__ 总是会引用该方法实际所在的类。当然,除非您在后代类中显式重写该方法。这称为后期静态绑定。
当我需要在 5.2 中实现 LSB 时,我通常会创建一个静态属性和相应的静态访问器,它们允许我更改由静态调用实例化的类。这里唯一的事情是,这仍然假设您只会使用单个后代,因为更改静态属性将全面更改它。它可以快速工作,具体取决于项目/应用程序/模块/包的实际架构。
The problem is in < php 5.3 the static method is always going to create an instance of the hard coded class. So if you are actually using
MyAdvancedDate
which extendsDate
youre always going to get an instance of the parent becauseself
and__CLASS__
are always going to refer to the class the method is actually in. This is ofcourse unless you override the method explicitly in the descendent classes. This is called Late Static Binding.When i need to implement LSB in 5.2 i generally make a static property and corresponding static accessors that allow me to change the class instantiated by static calls. The only thing here is this still assumes you are only ever going to use a single descedent as changing the static property will change it across the board. It can work in a punch though depending on what the actual architecture of the project/app/module/package.