2013-03-06 123 views
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; 

正如你可以看到,我试图用“格式(‘YM-d’)”很多次,不想它在多个地方类型,所以我试图简单地把它放在一个变量中并使用它。但是,我收到通知:消息:未定义的属性:DateTime :: $ format('Y-m-d')

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

+0

另一个“我怎样才能减少我在做我的代码不可读的费用键入击键次数”问题 – 2013-03-06 14:47:11

回答

4

没有,但你可以咖喱功能:

$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()) {... 
+0

值+1只是为了看问题的合理答案 – 2013-03-06 14:48:02

+0

更好地改变为公共函数格式($ format =“Ymd”),因为稍后以不同的参数调用代码格式:$ posted_on-> format('F jS,Y ') – palindrom 2013-03-06 14:50:07

+0

@palindrom谢谢,我已经编辑了相应的答案。 – 2013-03-06 14:50:55

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

我认为,这是不可能做到我想要的,包括功能本身。我只是好奇而已。谢谢。 – 2013-03-06 14:46:26

+0

@ user371699是的,但这也是可怕的。不要这样做。 – TFennis 2013-03-06 14:54:59

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'); 
} 
+0

我很欣赏这个答案,但我很想理解*为什么*它会很糟糕,为什么“$ interval-> format('%d')”会是“最好的选择” ”。这有什么不好?最后一个问题,如果$ posted_on也是今天,为什么两者之间的差异是0天? – 2013-03-06 15:45:34

+0

是的,你应该使用0和1,而不是1和2 :( – TFennis 2013-03-08 09:51:29

+0

那么你想要做什么就像$ interval-> getDays(),但PHP只允许你做$ interval-> d这是公开的可修改的(这反过来使我想吐)。 – TFennis 2013-03-08 09:52:59

相关问题