getmizanur Posted May 26, 2010 Share Posted May 26, 2010 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 Quote Link to comment https://forums.phpfreaks.com/topic/203021-need-help-to-understand-this-code/ Share on other sites More sharing options...
phpchamps Posted May 27, 2010 Share Posted May 27, 2010 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. Quote Link to comment https://forums.phpfreaks.com/topic/203021-need-help-to-understand-this-code/#findComment-1063965 Share on other sites More sharing options...
ignace Posted May 27, 2010 Share Posted May 27, 2010 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; Quote Link to comment https://forums.phpfreaks.com/topic/203021-need-help-to-understand-this-code/#findComment-1063990 Share on other sites More sharing options...
getmizanur Posted May 27, 2010 Author Share Posted May 27, 2010 Thanks guys. I thought it as much that it creates an new instance of itself. Quote Link to comment https://forums.phpfreaks.com/topic/203021-need-help-to-understand-this-code/#findComment-1064198 Share on other sites More sharing options...
ignace Posted May 29, 2010 Share Posted May 29, 2010 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. Quote Link to comment https://forums.phpfreaks.com/topic/203021-need-help-to-understand-this-code/#findComment-1064945 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.