Object to Array Conversion giving weird result

最后都变了- 提交于 2020-01-15 02:35:06

问题


I am trying to convert class to array. I am using following code:

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>';

Now the weird thing is the output:

Array
(
    [Propertyx] => 0
    [Propertyy] => 0
    [Propertyz] => 0
    [*x1] => 0
    [*y1] => 0
    [*z1] => 0
    [*x2] => 0
    [*y2] => 0
    [*z2] => 0
)

I want clean keys with no Class name and no * before key names.

Can anyone suggest me how to convert members names into array keys without class name and and without (*). Other solutions are also welcome.


回答1:


there is the special function

public function toArray() {
    return get_object_vars($this);
}

result

<pre>Array
(
    [x] => 0
    [y] => 0
    [z] => 0
    [x1] => 0
    [y1] => 0
    [z1] => 0
    [x2] => 0
    [y2] => 0
    [z2] => 0
)
</pre>

demo



来源:https://stackoverflow.com/questions/37317879/object-to-array-conversion-giving-weird-result

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!