2

As title suggests, My question is that how i can convert a php class to an associative array? For example I've

class MyObject {
  private $size = null;
  private $length = null;
  private $width = null;

    public function getSize(){
        return $this->size;
    }

    public function setSize($size){
        $this->size = $size;
    }

    public function getLength(){
        return $this->length;
    }

    public function setLength($length){
        $this->length = $length;
    }

    public function getWidth(){
        return $this->width;
    }

    public function setWidth($width){
        $this->width = $width;
    }

}

//Now what i want is following

$abc = new MyObject();
$abc->width = 10;
$anArray = someFunction($abc);  
//This should generate an associative array
//Now associative array is accessible
echo $anArray['width]; // 10
Aqeel Ahmad
  • 473
  • 8
  • 14

1 Answers1

8

There are two ways that work slightly differently.

You can cast to an array:

$array = (array)$object;

there's a chapter on details and side-effects in the PHP manual

or use get_object_vars().

See this question about the differences.

Community
  • 1
  • 1
Pekka
  • 442,112
  • 142
  • 972
  • 1,088
  • Can you please define that how to use get_object_vars() to build an associative array? – Aqeel Ahmad Oct 25 '10 at 11:48
  • @Aqeel Sorry if this comes across rude now, but did you actually [RTFM](http://en.wikipedia.org/wiki/RTFM "Read the f*cking Manual") before asking Pekka to spoonfeed you the code? If so, please point out what is making difficulties. – Gordon Oct 25 '10 at 11:50
  • @Gordon Sorry i'd a bit of confusion, I've solved my problems. Thanks. – Aqeel Ahmad Oct 25 '10 at 11:52