user34790
user34790

Reputation: 2036

Create actual copy of variables passed by reference in php

Actually, I have a function where a certain variable is passed as argument by reference. I want to create an actual copy of this variable inside my function instead of having a reference. How can I accomplish this in php?

Upvotes: 1

Views: 88

Answers (1)

Maxim Krizhanovsky
Maxim Krizhanovsky

Reputation: 26699

References in PHP do not work as pointers; actually variables in PHP are zval structures, and they contain information for the ref count, is the variable a reference and so on. This works transparently for you, and all that matters when you are using a reference is that you are modifying the original object, and possibly use less memory.

So, if you want to work with a fresh copy of the variable, to be safe from modifications, you can do:

$new_copy = $copy;

or if $copy is an object:

$new_copy = clone $copy;

Upvotes: 1

Related Questions