Search code examples
phpimagickimage-compression

PHP Imagick setImageCompression


I'm just starting to write some PHP using the Imagick / ImageMagick library, and have seen several examples regarding setImageCompression which appear to implement things differently.

For example I've seen it used like this:

$image->setImageCompression(Imagick::COMPRESSION_LZW);

and also like this:

$image->setImageCompression(\Imagick::COMPRESSION_UNDEFINED);

So, what is the relevance of the backslash before declaring the compression type? Is this specific to the compression type? A typo in examples I've seen or something else?


Solution

  • The backslash is only necessary when using namespaces.

    For instance, the former won't work in namespace Foo because it will look for a class Foo\Imagick:

    namespace {
        var_dump(Imagick::COMPRESSION_LZW); // int(11)
    }
    
    namespace Foo {
        var_dump(Imagick::COMPRESSION_LZW); // Class 'Foo\Imagick' not found
    }
    

    The second will work in all cases:

    namespace {
        var_dump(\Imagick::COMPRESSION_LZW); // int(11)
    }
    
    namespace Foo {
        var_dump(\Imagick::COMPRESSION_LZW); // int(11)
    }