2013-03-06 43 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

相關問題