Jump to content

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.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.