我想创建一个对象,它将参数带入其构造函数,然后返回一个关联数组。例如:使用一个对象来创建关联数组
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