2012-01-18 1 views
3

clone에 연쇄를 사용하여 메서드를 호출하는 인스턴스가 가능합니까?인스턴스 복제 및 메서드 호출 연결 가능?

/** 
* Parse an object containing (eventually) "duration" property or "year" (and 
* eventually) "month" properties. 
* 
* @return array Array containing start date and end date DateTime objects. 
*/ 
public function parseTimeArgs($args) 
{ 
    $now = new DateTime(); 

    if(isset($args->duration) && $duration = new DateInterval($args->duration)) 
     return array((clone $now)->sub($duration), $now); 
} 

답변

0

아니, 이것이 불가능이 나에게 구문 오류을 제공합니다.

public function parseTimeArgs($args) 
{ 
    $now = new DateTime(); 

    if(isset($args->duration) && $duration = new DateInterval($args->duration)) 
     return array($this->clone($now)->sub($duration), $now); 
} 

public function clone($object) 
{ 
    return clone $object; 
} 

사이드 참고 : 다음 new 연산자를 사용하면 이러한 방법 중 하나를하실 수 없습니다 당신은 대신 "공장"방법을 사용할 수 있습니다.

$a = (new a())->doStuff()->foMoreStuff(); 

복제 그러나 여기에서 지원되지 않습니다 다음과 같이 곧 PHP 5.4 버전에서는이 new 가능 할 것이다.

-1
public function parseTimeArgs($args) 
{ 
    $now = new DateTime(); 
    $nowClone = clone $now; 

    if(isset($args->duration) && $duration = new DateInterval($args->duration)) 
     return array($nowClone->sub($duration), $now); 
} 
+0

네, 그게 옳은 방법이라는 것을 이해하는 것은 어렵지 않지만 체인 연결에 대해서 말하고 있습니다 :'(clone $ now) -> method()'. – Polmonino

관련 문제