使用对象创建关联阵列


Using an object to create associative arrays

我正在尝试创建一个对象,该对象将参数带入其构造函数,然后返回一个关联数组。例如:

class RefArray {
    public $ref_id,$title,$pub_date,$doi,$author_name;
    public function __construct($ref_id, $title, $pub_date, $doi, $author_name){
        $this = array('ref_id'=>$this->ref_id, 'title'=>$this->title, 
         'pub_date'=>$this->pub_date, 'doi'=> $this->doi, 
         'author_name'=>$this->author_name);
    }
}

然而,上面的代码给出了这个错误:致命错误:无法重新分配$this

我这样做的原因是为了绕过PHP中不能有多个构造函数的限制(引用类在其构造函数中使用数组)。

class Reference {
    private $ref_id, $title, $pub_date, $doi, $external_ref_id, $author_name;
    public function __construct($refArray){
        $this->setRefId($refArray["ref_id"]);
        $this->setTitle($refArray["title"]);
        $this->setPubDate($refArray["pub_date"]);
        if(array_key_exists('doi', $refArray)){
            $this->setDoi($refArray["doi"]);
        }
        $this->setExtRef();
        if(array_key_exists('author_name', $refArray)){
            $this->setAuthor($refArray["author_name"]);
        }
    }

所以我的问题首先是,让一个类来创建一个关联数组的想法是否好。第二,如果是这样,我该如何让它发挥作用?

不,这不是个好主意。如果你需要一个对象作为数组,你可以直接键入它:

$arr = (array) $obj;

参见https://stackoverflow.com/a/4345609/413531

多重结构的问题是一个古老的问题;)

请参阅在PHP中执行多个构造函数的最佳方法,了解一些可能的解决方案。