duandao7704 2013-03-06 14:41
浏览 14
已采纳

是否有可能让函数变量包含参数?

I have the following code:

$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;

As you can see I'm trying to use "format('Y-m-d')" many times, and don't want to type it in multiple places, so I'm trying to simply put it in a variable and use that. However, I get a notice: Message: Undefined property: DateTime::$format('Y-m-d')

What would be the right way to go about doing this?

  • 写回答

3条回答 默认 最新

  • douliandan7340 2013-03-06 14:47
    关注

    No, but you can curry the function:

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

    Or more cleanly:

    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()) {...
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?