【问题标题】:Using an object to create associative arrays使用对象创建关联数组
【发布时间】: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 被分配为一个数组。感谢您的帮助!
  • 这里有一些严厉的反对意见......成为新手是程序员生活中必不可少的一部分,虽然很笨,但至少表现得很好并且需要付出一些努力......

标签: php arrays oop


【解决方案1】:

不,这不是一个好主意。如果你需要一个对象作为数组,你可以直接对它进行类型转换:

$arr = (array) $obj;

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

多重构造的问题是老问题了;)

请参阅Best way to do multiple constructors in PHP 了解一些可能的解决方案。

【讨论】:

  • 啊,谢谢您的回复!非常感激。 :) 是否有任何理由说明为什么这是一个坏主意?
  • 我指的是So my question firstly is whether or not the idea of having a class to make an associative array is a good one. - 如果功能是内置的,则无需构建这样的类。
猜你喜欢
  • 1970-01-01
  • 2012-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-27
  • 1970-01-01
  • 1970-01-01
  • 2017-05-28
相关资源
最近更新 更多