【发布时间】:2014-10-23 15:31:33
【问题描述】:
我正在尝试创建一个对象,该对象将参数带入其构造函数,然后返回一个关联数组。例如:
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"]);
}
}
所以我的问题首先是有一个类来创建一个关联数组的想法是否是一个好的想法。其次,如果它是如何使它工作的?
【问题讨论】:
-
"PHP 不允许我这样做,我如何强制 PHP 让我这样做"?这就是你的意思吗?你可以将任何你想要的东西传递给你的构造函数,然后将这些东西分配到任何你想要的地方,除了试图覆盖
$this。 -
@MarcB 当您这样说时,尝试去做似乎是一件相当愚蠢的事情。 :) 我没有意识到我试图覆盖
$this,我认为$this被分配为一个数组。感谢您的帮助! -
这里有一些严厉的反对意见......成为新手是程序员生活中必不可少的一部分,虽然很笨,但至少表现得很好并且需要付出一些努力......