Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Pass by Reference Issue

So I am having a strange issue where the functions are NOT defined by pass by reference parameters, yet objects are being changed in ways that I cannot explain. I have verified function definitions are not pass by reference time and time again. I have retrieved an object from the DB. Then I have run an analysis function on that initial object. I have copied the object to another variable. Then I run a different analysis function on the copy and not the original. Running the second analysis function seems to alter the first variable-object. Any ideas on what might be going on here. I have been trying to debug this for hours upon hours and I cannot explain this behavior. I would prefer not to post the the actual functions as they are proprietary information, however, I can possibly send them privately for some help. I thank you kindly for your time in trying to help me.

//get object from db
$resp= json_decode($ln->getResponseFromDb($resultid)); 

//run pwf analysis function
$resp = $ln->pwfBGCheck($resp);

//show result after pwf
print_r($resp->pwf);

/* shows
* stdClass Object ( [status] => p [reason] => Person has no c record. ) 
*/ 

//copy to another variable
$r2 = $resp;
//run pwf for s record other variable so it is not touching the first one!
$r2 = $ln->pwfBGCheckSexOffender2($r2);
echo '<BR>this is first variable<BR>';
print_r($resp->pwf);
/* copies from second to first for some reason... no pass by reference on this call...       resp variable has not been touched!
* stdClass Object ( [status] => p [reason] => Person has no s record. ) 
*/ 
echo '<BR>this is second<BR>';
print_r($r2->pwf);
/* returns
* stdClass Object ( [status] => p [reason] => Person has no s record. )
*/
like image 651
Mauricio Zuniga Avatar asked Sep 02 '26 18:09

Mauricio Zuniga


1 Answers

Since PHP5 object always pass by reference. If you want to get copy of object you have to use clone.

Objects and references

An exception to the usual assignment by value behaviour within PHP occurs with objects, which are assigned by reference in PHP 5. Objects may be explicitly copied via the clone keyword.

Assignment Operators

like image 74
sectus Avatar answered Sep 04 '26 08:09

sectus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!