PHP - 在__construct中设置一个数组

时间:2015-02-19 01:51:46

标签: php arrays oop file-upload

我正在创建一个上传课程,我想知道这是否正确..例如

private $fieldname; //setting name in form
    private $type = array(); //type files: text/plain','application/msword','application/pdf
    private $folder; //folder where save my files
    private $filename; //filename :)

    public function __construct($fieldname,$type,$folder,$filename){
        $this->fieldname = $fieldname;
        $this->type[] = $type;
        $this->folder = $folder;
        $this->filename = $filename;        
    }

当我实例化我的对象时

$upload = new UploadClass('file',['pdf','photo'],'folder','filename');

结果并不令我高兴

object(UploadClass)[1]
  private 'fieldname' => string 'file' (length=4)
  private 'type' => 
    array (size=1)
      0 => 
        array (size=2)
          0 => string 'pdf' (length=3)
          1 => string 'photo' (length=5)
  private 'folder' => string 'folder' (length=6)
  private 'filename' => string 'filename' (length=8)

我认为有两个阵列的问题并不酷...我不知道..也许你帮助我这变得更好..对不起代码!哈哈

1 个答案:

答案 0 :(得分:2)

因为UploadClass::type被声明为一个数组而你正在用$this->type[] = $type;向它添加一个元素,你会看到那个结果(即一个嵌套数组)。基本上,您将该数组添加到UploadClass::type的第一个元素。

只需将该数组分配给UploadClass::type即可全部设置:

$this->type = $type;