-1

My function getUser() does a databse select of user info. In this function, I call a another function called calcPercentage() which takes the received values from the database stored in $result, then removes some values(indexes) and do a calculation. Once complete, the second function returns a value to the first function.

My issue is that the values removed in calcPercentage(), the second function, are effecting the original values received from the database.

See code

function getUser()
{
  $result = DB::select();
// say $result = name, surname, email, telephone

  $percentage = $this->calcPercentage($result);

var_dump($result)
// now $result = name, surname
}

function calcPercentage($data)
{
 $u_data = $data;
 unset($u_data->email);
 unset($u_data->telephone);
 // the above values are not needed for the calculations,
 // thus they are being removed.

 ... do calculation
 return $percentage
 //$percentage would be = 100 || >100;
}

I would like to remove the values from the object with out affecting the original variable in function getUser(); Expected outcome.

function getUser()
{
  $result = DB::select();
// say $result = name, surname, email, telephone

  $percentage = $this->calcPercentage($result);

var_dump($result)
// now $result = name, surname, email, telephone
}

Should I rather do a another query here to the database?

1 Answers1

2

Before calling calcPercentage() method, clone your result object.

function getUser(){ 
    $result = DB::select();
    // say $result = name, surname, email, telephone

    $result_copy = clone $result;
    $percentage = $this->calcPercentage(result_copy);

    var_dump($result)
    // now $result= name, surname, email, telephone
}
yivi
  • 42,438
  • 18
  • 116
  • 138
Asif Rahaman
  • 775
  • 6
  • 10