2011-12-10 2 views
1
$currentDT = new \DateTime(); 
$filterRange = new \DateInterval('PT30S'); 
$filterDate = $currentDT->sub($filterRange); 
var_dump($currentDT); 
var_dump($filterDate); 

출력 :PHP 날짜 하위 문제

object(DateTime)[246] 
    public 'date' => string '2011-12-10 15:53:42' (length=19) 
    public 'timezone_type' => int 3 
    public 'timezone' => string 'America/New_York' (length=16) 
object(DateTime)[246] 
    public 'date' => string '2011-12-10 15:53:42' (length=19) 
    public 'timezone_type' => int 3 
    public 'timezone' => string 'America/New_York' (length=16) 

서로 다른 30 대 있어야한다하더라도 $ currentDT 및 $ filterDate이 ... 동일합니다. 왜 그런가?

답변

7

예상되는 동작이므로, 원래 개체에 대해 뺄셈이 수행 된 다음 반환됩니다. 이는 var_dump() 출력의 246에서 볼 수 있습니다. 출력은 하나의 동일한 객체임을 나타냅니다.

원본 개체를 그대로 유지하려면 뺄셈을 수행하기 전에 clone해야합니다.

$currentDT = new \DateTime('2011-12-13 14:15:16'); 
$filterRange = new \DateInterval('PT30S'); 
$filterDate = clone $currentDT; 
$filterDate->sub($filterRange); 
var_dump($currentDT, $filterDate); 
0

DateTime::sub은 현재 객체의 날짜를 변경하고 메소드 체인을 위해 사본을 반환합니다. 따라서 예에서 두 개체의 날짜가 변경되므로 두 개체 모두 30 초 전에 설정됩니다.

이 시도 - 그것은 비교를 위해 두 개의 별도 초기화 객체를 사용 @salathe가 지적으로

$current1 = new \DateTime(); 
$current2 = new \DateTime(); 

$filterRange = new \DateInterval('PT30S'); 
$current2->sub($filterRange); 
var_dump($current1); // Should return the current time 
var_dump($current2); // Should return the current time - 30 seconds 

또는, 물론 clone 키워드를 사용합니다.

0

INSTANCE1 및 인스턴스 2는 서버의 처리 속도에 따라 동일하지 않고있는 기회가 있기 때문에, 날짜의 2 연속 isntances를 만드는 대신 복제되어 갈 수있는 유일한 방법입니다.