Skip to content

Instantly share code, notes, and snippets.

@romainneutron
Created November 29, 2012 23:04
Show Gist options
  • Save romainneutron/4172521 to your computer and use it in GitHub Desktop.
Save romainneutron/4172521 to your computer and use it in GitHub Desktop.
Image destructor issue
<?php
class Imagine
{
function open($path)
{
return new Image(new \Gmagick($path));
}
}
class Layers implements Countable
{
private $resource;
function __construct(\Gmagick $resource)
{
$this->resource = $resource;
}
function count()
{
return $this->resource->getnumberimages();
}
}
class Image
{
private $resource;
public static $destructorActivated = false;
function __construct(\Gmagick $resource)
{
$this->resource = $resource;
}
function __destruct()
{
if(self::$destructorActivated) {
$this->resource->clear();
$this->resource->destroy();
}
}
function layers()
{
return new Layers($this->resource);
}
}
$imageFile = 'image.gif';
// everything alright
$imagine = new Imagine();
$image = $imagine->open($imageFile);
echo sprintf("image has %d layers\n", count($image->layers()));
// everything alright
$imagine = new Imagine();
echo sprintf("image has %d layers\n", count($imagine->open($imageFile)->layers()));
// changing configuration
Image::$destructorActivated = true;
// everything alright
$imagine = new Imagine();
$image = $imagine->open($imageFile);
echo sprintf("image has %d layers\n", count($image->layers()));
// This fails, will print "image has 0 layers"
$imagine = new Imagine();
echo sprintf("image has %d layers\n", count($imagine->open($imageFile)->layers()));
@avalanche123
Copy link

how about this:

<?php

class Layers
{
    public function __construct(Image $image, \Gmagick $resource)
    {
        $this->image = $image; // just a trick to preserve image reference, to prevent it from being garbage collected until we're done with layers object
        $this->resource = $resource;
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment