Dan Dan - 5 months ago 7x
PHP Question

Return object instance with current state

Are there any differences between

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


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


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;


AS an example if you do this

 $test = new TestCase;


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;

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.
 $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.