代码之家  ›  专栏  ›  技术社区  ›  Stark

如何查看和返回if语句中使用的函数的结果?

php
  •  0
  • Stark  · 技术社区  · 7 年前

    我遇到了以下问题 $image_name uploadImage function 我不能退还 $image\u名称 所以我可以把它插入数据库,我不知道如何返回那个变量。

    public function uploadImage($data, $uploadLocation, $nameTag){
        if($data['size'] != 0) {
            $errors     = array();
            $maxsize    = 16777216;
            $acceptable = array(
                'image/jpeg',
                'image/jpg',
            );
            $image_extension = pathinfo($data['name'], PATHINFO_EXTENSION);
    
            //image_name variable I'm referring to
            $image_name = uniqid($nameTag, true) . '.' . $image_extension;
    
            if($data['size'] >= $maxsize) {
                $errors[] = 'File too large. File must be less than 16 megabytes.';
            } else if($data['size'] == 0){
                $errors[] = 'You need to upload an image.';
            }
    
            if((!in_array($data['type'], $acceptable)) || (empty($data['type']))) {
                $errors[] = 'Invalid file type. Only JPG, GIF and PNG types are accepted.';
            }
    
            if(count($errors) === 0) {
                $moveFile = move_uploaded_file($data['tmp_name'], $uploadLocation . '/' . $image_name );
    
                if($moveFile){
                    return true;
                }
            }
        }
    
        return false;
    }
    

    $uploadImage = new UploadImages();
    
    if($uploadImage->uploadImage($data['image_data'], 'uploads/img/instructions', 'instruction_')){
    
        //here I'd like to return the $image_name from the function
        //I'm using PDO to insert the name in database
        $sth = $db->prepare('UPDATE instructions SET image = :image WHERE id = :id');
        $sth->bindValue(':image', //name returned from the function, PDO::PARAM_STR );
        $sth->bindValue(':id', $instructionsId, PDO::PARAM_INT);
        $sth->execute();
    }
    

    我认为在这段代码中:

    if($moveFile){
        return true;
    }
    

    我可以退回 $image\u名称

    4 回复  |  直到 7 年前
        1
  •  1
  •   Rasclatt    7 年前

    在我的评论之后,我可能会考虑类似的结构:

    class UploadImages
        {
            # Save all your persisting variables
            protected $errors = array();
            protected $image_name,
                      $success = false;
            # You may want to make this editable in the future
            protected $maxsize = 16777216;
            # You may want to add more mimes later
            protected $acceptable = array(
                          'image/jpeg',
                          'image/jpg',
                      );
            # Make a listener
            public function listen($data, $uploadLocation, $nameTag)
            {
                if(!empty($data['size'])) {
                    $image_extension = pathinfo($data['name'], PATHINFO_EXTENSION);
                    # Store the file name
                    $this->image_name = uniqid($nameTag, true) . '.' . $image_extension;
                    # Use the editable variable
                    if($data['size'] >= $this->maxsize) {
                        # Store error
                        $this->errors[] = 'File too large. File must be less than 16 megabytes.';
                    }
                    # Check editable mime
                    if((!in_array($data['type'], $this->acceptable)) || (empty($data['type']))) {
                        $this->errors[] = 'Invalid file type. Only JPG, GIF and PNG types are accepted.';
                    }
                    # Store the success
                    if(count($this->errors) === 0) {
                        $this->success = move_uploaded_file($data['tmp_name'], $uploadLocation . '/' . $this->image_name );
                    }
                } else {
                    $this->errors[] = 'You need to upload an image.';
                }
                # Return the object
                return $this;
            }
    
            public function getFileName()
            {
                return $this->image_name;
            }
    
            public function isUploaded()
            {
                return $this->success;
            }
    
            public function getErrors()
            {
                return $this->errors;
            }
    
            public function hasErrors()
            {
                return (!empty($this->errors));
            }
        }
    # Create the class, since the listen() method returns the object, you can
    # run that right off the top
    $uploadImage = (new UploadImages())->listen($data['image_data'], 'uploads/img/instructions', 'instruction_');
    # Check if there are errors or if the upload itself failed
    if($uploadImage->hasErrors() || !$uploadImage->isUploaded()) {
        # Write the error depending on which error occurred
        echo ($uploadImage->hasErrors())? implode('<br />',$uploadImage->getErrors()) : 'Your upload failed do to an unknown error.';
    }
    else {
        # Fetch name on success
        $img = $uploadImage->getName();
        $sth = $db->prepare('UPDATE instructions SET image = ? WHERE id = ?');
        $sth->execute(array($img,$instructionsId));
    }
    
        2
  •  1
  •   arthooz    7 年前

    你可以把它存储在 UploadImages

        3
  •  0
  •   B. Desai    7 年前

    你可以回来 $image_name true false / null or 0 价值

    if($moveFile){
       return $image_name; //you can add file name here
    }
    

    //Following condition become true if function return file name and not `false`
    if($image_name = $uploadImage->uploadImage($data['image_data'], 'uploads/img/instructions', 'instruction_')){
         //You can use filename now
        //here I'd like to return the $image_name from the function
        //I'm using PDO to insert the name in database
        $sth = $db->prepare('UPDATE instructions SET image = :image WHERE id = :id');
        $sth->bindValue(':image', //name returned from the function, PDO::PARAM_STR );
        $sth->bindValue(':id', $instructionsId, PDO::PARAM_INT);
        $sth->execute();
    }
    
        4
  •  0
  •   Cuagau    7 年前

    有几种方法可以做到这一点。首先,您确实需要在成功时返回$image\u名称,而不是true。然后你可以做

    $filename = $uploadImage->uploadImage($data['image_data'], 'uploads/img/instructions', 'instruction_');
    if($filename !== false){ //uploadImage returns false on error
      ...
    

    if($filename = $uploadImage->uploadImage($data['image_data'], 'uploads/img/instructions', 'instruction_')){
    

    推荐文章