Need Help Understanding this PHP Code

前端 未结 5 1562
感情败类
感情败类 2021-01-23 07:48

i am aware of the basics like what is a function, a class, a method etc. however i am totally confused on what exactly the below code does to read the image, i read it somewhere

5条回答
  •  独厮守ぢ
    2021-01-23 08:46

    Your $image would contain an instance of the Image Class.

    Your constructor will try to open $filename. If that's not possible, the script will die/terminate with an error message. If $filename can be opened, the file will be read into the $buf variable and a GD image resource will be created.

    The code is suboptimal for a number of reasons:

    1. the GD resource created by imagecreatefromstring is not assigned to a property of the Image class. This means, the entire process is pointless, because the resource will be lost after it was created. The work done in the constructor is lost.

    2. calling die will terminate the script. There is no way to get around this. It would be better to throw an Exception to let the developer decide whether s/he wants the script to terminate or catch and handle this situation.

    3. reading a file with fopen and fread works, but file_get_contents is the preferred way to read the contents of a file into a string. It will use memory mapping techniques if supported by your OS to enhance performance.

    4. You should not do work in the constructor. It is harmful to testability.

    A better approach would be to use

    class Image
    {
        protected $_gdResource;
    
        public function loadFromFile($fileName)
        {
            $this->_gdResource = imagecreatefromstring(
                file_get_contents($fileName)
            );
            if(FALSE === $this->_gdResource) {
                throw new InvalidArgumentException(
                    'Could not create GD Resource from given filename. ' .
                    'Make sure filename is readable and contains an image type ' .
                    'supported by GD'
                );
            }
        }
    
        // other methods working with $_gdResource … 
    }
    

    Then you can do

    $image = new Image;             // to create an empty Image instance
    $image->loadFromFile('pic.jpg') // to load a GD resource
    

提交回复
热议问题