[英]How can I convert an object to associative array in PHP?
As title suggests, My question is that how i can convert a php class to an associative array? 如标题所示,我的问题是我如何将php类转换为关联数组? 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
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 PHP手册中有一章介绍了详细信息和副作用
or use get_object_vars()
. 或使用
get_object_vars()
。
See this question about the differences. 请参阅有关差异的问题 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.