我一次又一次地遇到这个问题:
您有一个具有日期(日期时间) $object->date的对象,它以几种格式表示
在最前面.在某些情况下,可以是空的。
所以我通常的方法是在模型中:
public function getDate(){
if($this->date){
return DateTime($this->date);
}
return null;
}并在$object->getDate()->format('d-m-Y')中使用;
这很酷..。但如前所述,可能有些对象的日期为空,
而上述调用将导致"...format() on a non object...“异常。
这方面的工作是始终检查是否为空:
$object->getDate() ? $object->getDate()->format('d-m-Y') : "";
这太长太丑了,每次你需要约会的时候都不能用。
因此,我的最后解决方案是将检查合并到方法中:
public function getDate($format = false, $empty_str = ""){
if($format){
if($this->date){
$dt = new DateTime($this->date);
return $dt->format($format);
}
return $empty_str;
}else{
return new DateTime($this->date);
}
}编辑:在几年后回顾了我的代码,我想出了更好的格式:
public function getDate($format = false, $empty_str = ""){
if (!$this->date) {
return $empty_str;
}
$dt = new DateTime($this->date);
return ($format) ? $dt->format($format) : $dt;
}它的用法很酷:
$object->getDate('d-m-Y');
$object->getDate('d-m-Y', 'no date');
$object->getDate(); // DateTime object我唯一关心的是..。该方法破坏了几个OOP原则,而且看起来太自定义了。
有什么更好的方法吗?这是一个常见的问题,所以应该有一个好的解决方案。
发布于 2014-01-09 09:42:50
您可以编写一个特定的类,如
class NullObject {
public function __get($var) {
return null;
}
public function __call($funcname, $params) {
return null;
}
}而不是简单地返回null,而是这样做
return new NullObject();发布于 2014-01-09 09:31:51
public function getDate($format = "default format", $empty_str = ""){
if($this->date){
$dt = new DateTime($this->date);
return $dt->format($format);
}
return $empty_str;
}https://stackoverflow.com/questions/21016089
复制相似问题