0

我有以下代码:

$posted_on = new DateTime($date_started);
$today = new DateTime('today');
$yesterday = new DateTime('yesterday');
$myFormat = 'format(\'Y-m-d\')';

if($posted_on->{$myFormat} == $today->{$myFormat}) {
    $post_date = 'Today';
}
elseif($posted_on->{$myFormat} == $yesterday->{$myFormat}) {
    $post_date = 'Yesterday';
}
else{
    $post_date = $posted_on->format('F jS, Y');
}

echo 'Started '.$post_date;

正如你所看到的,我试图多次使用“format('Ymd')”,并且不想在多个地方输入它,所以我试图简单地将它放在一个变量中并使用它。但是,我收到一条通知:消息:未定义属性:DateTime::$format('Ymd')

这样做的正确方法是什么?

4

3 回答 3

5
$myFormat = 'Y-m-d';
...
$today->format($myFormat);
...
于 2013-03-06T14:43:55.860 回答
4

不,但您可以对函数进行 curry:

$myFormat = function($obj) {return $obj->format("Y-m-d");};

if( $myFormat($posted_on) == $myFormat($today))

或者更干净:

class MyDateTime extends DateTime {
    public function format($fmt="Y-m-d") {
        return parent::format($fmt);
    }
}
$posted_on = new MyDateTime($date_started);
$today = new MyDateTime("today");
$yesterday = new MyDateTime("yesterday");

if( $posted_on->format() == $today->format()) {...
于 2013-03-06T14:47:02.997 回答
1
$posted_on = new DateTime($date_started);
$today = new DateTime('today');
$yesterday = new DateTime('yesterday');
$myFormat = 'Y-m-d';

if($posted_on->format($myFormat) == $today->format($myFormat)) {
    $post_date = 'Today';
}
elseif($posted_on->format($myFormat) == $yesterday->($myFormat)) {
    $post_date = 'Yesterday';
}
else{
    $post_date = $posted_on->format('F jS, Y');
}

echo 'Started '.$post_date;

这是你能做的最好的。我会将格式放在常量或配置文件中的某个位置,但 w/e. 你试图做的事情是可能的,但它太可怕了,当我读到它时我真的开始哭了。

同样在这种情况下,我会做这样的事情

$interval   = $posted_on->diff(new DateTime('today'));
$postAge    = $interval->format('%d'); // Seems to be the best out of many horrible options
if($postAge == 1)
{
    $post_date = 'Today';
}
else if($postAge == 2)
{
    $post_date = 'Yesterday';
}
else
{
    $post_date = $posted_on->format('F jS, Y');
}
于 2013-03-06T14:53:09.073 回答