Jump to content

Need help to understand this code


getmizanur

Recommended Posts

elloo,

 

i saw this code today and it struck some interest in me 'cause i had not seen this style of coding in foreach statement before.

 

class Test
  {
          public $testString = "value";
          public $testString1 = "value1";
          private $testString2 = "value2";
  
          public function &do_something()
          {   
                  eval('$rtn=new ' . get_class($this) . ';');

                  foreach($this as $prop => $val)
                  {   
                          $rtn->$prop=$val;
                  }   
  
                  return $rtn;
          }   
  }
$obj = new Test();
print_r($obj->do_something());

 

i'm tiny bit baffled by the line

 

$rtn->$prop=$val

 

what does the function &do_somthing() do?

 

many thanks in advance

Link to comment
https://forums.phpfreaks.com/topic/203021-need-help-to-understand-this-code/
Share on other sites

It creates the object of the class Test. sets up the properties of the class with their corresponding values and returns back the object by reference.

 

So, line

 eval('$rtn=new ' . get_class($this) . ';'); 

 

creates the object of test class. foreach sets the properties values and return statement returns the object by reference.

do_something doesn't need the reference-operator (&) as objects are always passed by reference. do_something clones the current object and returns it, so the same as:

 

function do_something() {
  return clone $this;
}

 

do_something is unnecessary here as you can just do:

 

$test = new Test();
$test2 = clone $test;

Thanks guys. I thought it as much that it creates an new instance of itself.

 

It creates a clone of the existing instance. If you are using PHP5 (and you should as PHP4 is deprecated) I highly advise you to drop this code and use the clone keyword instead.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.