如何在PHP中将对象转换为关联数组?

时间:2010-10-25 11:34:52

标签: php

正如标题所示,我的问题是我如何将php类转换为关联数组? 例如我

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

1 个答案:

答案 0 :(得分:7)

有两种方式略有不同。

您可以转换为数组:

$array = (array)$object;

有关于细节和副作用的章节in the PHP manual

或使用get_object_vars()

有关差异,请参阅this question