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

같은 것을 할 것 또 "나는 내 코드를 읽을 만들기의 비용으로 입력 할 필요가 키 입력의 수를 줄일 수있는 방법"질문 –

답변

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

가치가있는 질문에 대한 답변을 보려면 –

+0

나중에 다른 인수로 호출 된 코드 형식이므로 public 함수 형식 ($ format = "Ymd")으로 변경하는 것이 좋습니다. $ posted_on-> format ('F jS, Y ') – palindrom

+0

@palindrom 감사합니다. 그에 따라 대답을 편집했습니다. –

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

나는 그것을 받아 그 함수 자체를 포함하기 위해 내가 의도 한 바를 할 수는 없습니다. 나는 그것에 대해 궁금해했다. 고맙습니다. –

+0

@ user371699 예, 가능 합니다만, 또한 끔찍합니다. 그런 식으로하지 마십시오. – TFennis

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; 

당신이 할 수있는 최선이다. 내가 어딘가에 상수 또는 구성 파일에 승/전자 형식을 넣어 것입니다. 당신이하려고하는 것은 가능하지만 실제로 읽을 때 울기 시작한 것은 너무 무섭습니다.

가이 경우에 나는 아직이

$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 일이되지 않는 이유는 무엇입니까? –

+0

그래, 1과 2가 아닌 0과 1을 사용해야한다. ( – TFennis

+0

$ interval-> getDays()와 비슷하지만 PHP는 $ interval-> d를 public으로하고 수정할 수 있습니다. (차례 차례로 나는 토하고 싶다). – TFennis

관련 문제