正如标题所示,我的问题是我如何将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
Run Code Online (Sandbox Code Playgroud)
有两种方式略有不同.
你可以强制转换为数组:
$array = (array)$object;
Run Code Online (Sandbox Code Playgroud)
PHP手册中有关于细节和副作用的章节
关于差异,请参阅此问题.