Search code examples
phpobjectclonechaining

Cloning an instance and chaining a method call, possible?


Is possible to clone an instance calling a method on it with chaining? This gives me a syntax error:

/**
 * 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);
}

Solution

  • No, this is not possible. You could use a "factory" method instead:

    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;
    }
    

    Side note: Using the new operator is currently not possible this way either. In the upcoming PHP 5.4 release this will be possible for new as follows:

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

    Clone however is not supported here.