简体   繁体   中英

Return object instance with current state

Are there any differences between

$this->state = $state;
return $this;

and

$instance = clone $this;
$instance->state = $state;
return $instance;

Context:

class TestCase {

    /**
     * State
     */
    private $state;

    /**
     * Set state
     */
    function setState($state) {
        $this->state = $state;
        return $this;
        // Or
        // $instance = clone $this;
        // $instance->state = $state;
        // return $instance;
    }

}
$test = new TestCase;
$test->setState($state1)->setState($state2);

如果我没记错的话,克隆时会产生两个不同的对象。

AS an example if you do this

 $test = new TestCase;
 $test->setState(1)->setState(2);

 $test->getState();

Then what clone are you using, the answer is none, because $test is the original object which has never actually had it's state set. The other 2 clones are discarded at the end of the method chain.

The method chain may return the correct value, but if you take the obect $test into a different scope, such as

function a(){
      $this->test = new TestCase;
      $this->test->setState(1)->setState(2);
}

function b(){
    echo $this->test->setState(3);
}

Then test has never known about the other 2 states, as I said it's some what pointless.

Typically you would want to clone an object if you were forking it after setting some initial value. An example would be like a query builder, where you build the query and then clone it to do a separate query to count the results ( minus a limit or order for example )

 $Qb = new QueryBuilder();
 $Qb->select('*')->table('posts')->where( 'published', '<', '2014-02-20' );

  //copy and diverge to count results,
 $tQb = clone $Qb;
 $tQb->select('COUNT(id) AS total');  
 $total = $tQb->getResult();

  // add limits to original instance.
 $Qb->limit('20');
 $rows = $Qb->getResult();

See cloning would be used to save setting up the initial part of the query, then you copy and diverge them for the individual needs. One to count the total results one to pull a limited number of results. Which is useful if you had several joins and multiple parts to the where clause etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM