开发者

How do you explicitly create a copy of a variable in PHP?

I have an array of stdClass objects. When I assign one to a variable, it is not copying the variable but instead referencing the original variable. My code is like this:

for ( $i = 0, $len = count($rows); $i < $len; $i++ )
{
    $row = $rows[$i];
    echo $rows[$i]->games;
    $row->games = 'test';
    echo $rows[$i]->games;
}

The first echo outputs the normal value, but the second ech开发者_JAVA技巧o outputs "test". Even though I am setting the property on $row (which should be copied), it's actually setting it on the original array element.

Why is this, and how do I actually create a copy, so that modifying the copy doesn't modify the original?


Use the clone keyword.

$copy = clone $object;

important to note:

When an object is cloned, PHP 5 will perform a shallow copy of all of the object's properties. Any properties that are references to other variables, will remain references.

it comes with a nice magic method:

Once the cloning is complete, if a __clone() method is defined, then the newly created object's __clone() method will be called, to allow any necessary properties that need to be changed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜