对象数组转换给人怪异的结果 [英] Object to Array Conversion giving weird result

查看:94
本文介绍了对象数组转换给人怪异的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图类转换为数组。我使用以下code:

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

现在奇怪的是输出:

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

我要清洁键没有名称和键名不前,*。

任何人都可以建议我如何成员的名字转换成数组键无类名和和无(*)。其他解决方案也欢迎。

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

推荐答案

有特殊功能

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>

演示

这篇关于对象数组转换给人怪异的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆