php类没有执行else语句

时间:2012-02-01 18:20:33

标签: php oop

做一个菜鸟......我无法弄清楚这里有什么不行...... 如果文件为空,$this->result包含正确的错误消息。 但是,如果我有一个文件名,结果数组是空的,我没有上传

class upload_f
{
    public $path;              // path to upload from root ie  files/images/
    public $fileName;          // current file  ie $_FILES['uploadedfile']['name'];
    public $result = array();  // array containing error to be loop outside object

    public function validateInput()       // verify is minimal data is entered.
    {

        if (empty($this->fileName))
        {
            $this->result[] = "ERROR: File name is empty.";
            return false;
        }
    } // end of validate


    public function upload()
    {
        // run validation
        if (!$this->validateInput())
        {
            return $this->result;
        }
        else
        {
            $f_name = $this->fileName;
            $path_fileName = $this->path.$this->fileName;

            if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $path_fileName))
            {
                $this->result[] =
                    "File  ".  basename( $_FILES['uploadedfile']['name']). " was uploaded";
            }
            else
            {
                $this->result[] = "There was an error uploading the file, please try again!";
            }

            $this->result[] = $path_fileName;
            return  $this->result;

        } // end of else : upload execution if no errors
    }

} // end of upload class

[...]

//****************************************/

// call the object
// form here with a if - post ... 
$the_array = $test->upload();
$test = new upload_f();
// assgin values
$test->path = "docs/";
$test->fileName = $_FILES['uploadedfile']['name'];
$the_array = $test->upload();
echo "<pre>";
print_r ($the_array);
echo "</pre>";

2 个答案:

答案 0 :(得分:2)

您应该将validateInput()更改为:

public function validateInput() {    
    if (empty($this->fileName)) {
        $this->result[] = "ERROR: File name is empty.";
        return false;
    }
    return true; // <-- return true if input is valid
}

如果你拥有它,该方法会针对所有情况返回 falsy ,导致!$this->validateInput()始终评估为true

<强>参考

答案 1 :(得分:0)

不确定这是不是你的问题,但你在上传课程结束时错过了一个结束括号。

我注意到你的代码看到你使用花括号的奇怪风格。养成选择风格并坚持下去的习惯会很棒。你可以使用任何风格,只要它是一致的。以下是它们的列表:Indent Styles

相关问题