0

I've never had an issue like this before - in any language in fact.

I have an object originally from JSON. I don't want to alter this object, and will use it merely as a copy for various purposes.

In this example, the object I don't want to alter has lorem ipsum, as I've deemed the actual contents irrelevant.

//Inside the Object I don't want to alter, consider it a template/structure: {"random_key"=>"","another_random_key_with_an_int"=>1}

function random_func(){
    $local_scope_object = $this->original_instance;

    $local_scope_object->random_key = "now has data";

    return $local_scope_object;
}

As you can see above, there's an object returned to the handler, but lets ignore that for now.

When I var_dump($this->original_instance); I expect to see the instance unchanged, and its key random_key to remain empty; but it is affected.

What could this be, because I haven't declared the local scope var like (with the amp &) $local_scope_object = &$this->original_instance?

yivi
  • 42,438
  • 18
  • 116
  • 138
Mark Foxx
  • 7
  • 1
  • 1
    have you tried using the `clone` keyword? –  Feb 16 '19 at 15:07
  • I have indeed, but with no luck. I'm quite perplexed as my code in PHP, and the majority of languages I've used don't behave like this. I could rewrite my project, but I don't want to be defeated, and need to understand the issue. – Mark Foxx Feb 16 '19 at 15:14
  • Does my answer help explain it better at all? –  Feb 16 '19 at 15:16
  • Thanks for all the information, but the issue still remains. – Mark Foxx Feb 16 '19 at 15:19
  • Ah. Well sorry. I was sure that was it. –  Feb 16 '19 at 15:21
  • If that's not it, then I don't know what it would be. –  Feb 16 '19 at 15:22
  • Mark, there is no issue here. It's just that maybe you do not understand how instance assigment work in PHP. Read the duplicat target, it's perfectly explained there. If you do not want to affect the object, make a real copy via `clone`. – yivi Feb 16 '19 at 15:23
  • 1
    Oh no sorry guys, I don't know what I was thinking there with my previous response, it's all done WITH CLONE. – Mark Foxx Feb 16 '19 at 15:31
  • @yivi Should I delete my answer, or is it still useful you think? –  Feb 16 '19 at 15:35
  • @Chipster The answer is not wrong, but I do not personally see much value on it being better explained in the duplicate. If you want to add an answer, maybe is better to do it there. But of course, that's just muy opinion, you are free to do as you wish. – yivi Feb 16 '19 at 15:41
  • @yivi Well, I asked for your opinion, so thanks. I want the review queue, and that 1 down vote is keeping me from it, so I really want to delete ii. However since it was technically correct I didn't want just haul off and do it in case you or someone else thought it was still useful. –  Feb 16 '19 at 15:45

0 Answers0