如何在新变量中复制资源并销毁旧资源


How to copy resource in new variable and destroy old resource?

给定以下代码:

imagecopyresized($new_image, $product, $dst_x, $dst_y, $src_x, $src_y, $dst_width, $dst_height, $src_width, $src_height);
imagedestroy($product);
$product = $new_image;
imagedestroy($new_image);

最后一行破坏$product,而不仅仅是$new_image,就好像$product是指向$new_image的某种指针一样。为什么会发生这种情况?我如何在$product中有效地创建*$new_image*的副本,然后销毁$new_image资源?

发生这种情况的原因:

PHP使用写时复制内存管理,即不会在内存中为变量-->分配新的空间,只指向相同的内存位置。

如何避免这种情况:

imagecopyresized($new_image, $product, $dst_x, $dst_y, $src_x, $src_y, $dst_width, $dst_height, $src_width, $src_height);
imagedestroy($product);
$product = clone $new_image;
imagedestroy($new_image);

http://www.php.net/manual/en/language.oop5.cloning.php

关于写时复制:http://www.research.ibm.com/trl/people/mich/pub/200901_popl2009phpsem.pdf

$product$new_image相同资源的标识符。使用$product = clone $new_image;获取图像资源的副本。然后,您将能够在不破坏$product的情况下调用imagedestroy($new_image)