我想創建一個對象,它將參數帶入其構造函數,然後返回一個關聯數組。例如:使用一個對象來創建關聯數組
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);
}
}
然而,上面的代碼中給出了這樣的錯誤:致命錯誤:不能重新分配$這
我之所以這樣做是爲了避開不限制能夠在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"]);
}
}
所以我的問題首先是是否有一個類,以創建一個關聯數組是一個很好的想法。其次,如果它是我如何使它工作?
「PHP不讓我這樣做,我該如何強迫PHP讓我這樣做」?那是你在做什麼?你可以將你想要的任何東西傳遞給你的構造函數,然後將這些東西分配到任何你想要的地方,**除了**以覆蓋'$ this'外。 – 2014-08-29 15:27:17
@MarcB當你這樣說的時候,它看起來像是一件相當愚蠢的事情。 :)我沒有意識到我試圖覆蓋'$ this',我以爲'$ this'被分配爲一個數組。謝謝您的幫助! – TheCurlyProgrammer 2014-08-29 15:49:45
一些苛刻的downvotes在這裏...作爲newb是一個程序員的生活的一個必須的部分,雖然很不高興,這至少是表現,並提出一些努力... – 2014-08-29 16:14:36