函数变量是否可能已经包含参数


Is it possible to have function variables already include arguments?

我有以下代码:

$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('Y-m-d'(",不想在多个地方键入它,所以我试着简单地把它放在一个变量中并使用它。然而,我收到了一个通知:消息:未定义的属性:DateTime::$format('Y-m-d'(

做这件事的正确方法是什么?

$myFormat = 'Y-m-d';
...
$today->format($myFormat);
...

没有,但您可以使用函数:

$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()) {...
$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');
}