我正在尝试将类转换为数组。我使用以下代码:
class Abc{
private $x, $y, $z;
protected $x1, $y1, $z1;
protected $x2, $y2, $z2;
public function __construct() {
$this->x=$this->y=$this->z=$this->x1=$this->y1=$this->z1=$this->x2=$this->y2=$this->z2=0;
}
public function getData() {
return $x;
}
public function toArray() {
return (array)$this;
}
}
$abc = new Abc();
echo '<pre>', print_r($abc->toArray(), true), '</pre>';
现在奇怪的是输出:
Array
(
[Propertyx] => 0
[Propertyy] => 0
[Propertyz] => 0
[*x1] => 0
[*y1] => 0
[*z1] => 0
[*x2] => 0
[*y2] => 0
[*z2] => 0
)
我希望在密钥名称之前没有Class
名称且没有*的干净密钥。
任何人都可以建议我如何将成员名称转换为没有类名和没有(*)的数组键。其他解决方案也欢迎。
答案 0 :(得分:3)
有特殊功能
public function toArray() {
return get_object_vars($this);
}
结果
<pre>Array
(
[x] => 0
[y] => 0
[z] => 0
[x1] => 0
[y1] => 0
[z1] => 0
[x2] => 0
[y2] => 0
[z2] => 0
)
</pre>