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

Link to comment
Share on other sites

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;

Link to comment
Share on other sites

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.