-4

I am trying to create an object that takes parameters into its constructor and then gives back an associative array. For example :

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);
    }
}

However, the code above gives this error: Fatal error: Cannot re-assign $this

The reason why I do this is to get around the restriction of not being able to have more than one constructor in PHP (the reference class takes an array in it's constructor).

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"]);
        }
    }

So my question firstly is whether or not the idea of having a class to make an associative array is a good one. Secondly if it is how do I make it work?

  • 1
    "PHP doesn't let me do this, how can I force PHP to let me do it"? Is that what you're getting at? You can pass whatever you want into your constructor, and then assign that stuff wherever you want, **EXCEPT** for trying to overwrite `$this`. – Marc B Aug 29 '14 at 15:27
  • 1
    @MarcB When you put it like that, it does seem like a rather stupid thing to try and do. :) I did not realise that I was trying to overwrite `$this`, I thought `$this` was being assigned as an array. Thanks for the help! – TheCurlyProgrammer Aug 29 '14 at 15:49
  • some harsh downvotes here... being newb is a obligatory part of a programmer's life, and while quite noobish, this at least is behaved and presents some effort... – Félix Adriyel Gagnon-Grenier Aug 29 '14 at 16:14

1 Answers1

1

No, it's not a good idea. If you need an object as array, you can just typecast it:

$arr = (array) $obj;

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

The problem of multiple constructos is an old one ;)

see Best way to do multiple constructors in PHP for some possible solutions to work around it.

Community
  • 1
  • 1
Hirnhamster
  • 7,101
  • 8
  • 43
  • 73
  • Ah, thanks for the response! Much appreciated. :) Is there any reason specifically as to why this is a bad idea? – TheCurlyProgrammer Aug 29 '14 at 15:41
  • I was referring to `So my question firstly is whether or not the idea of having a class to make an associative array is a good one.` - There is no need to build such a class if the functionality is built-in. – Hirnhamster Aug 29 '14 at 15:46