2016-05-19 7 views
2

クラスを配列に変換しようとしています。ノーClass名とキー名の前に* NOでクリーンなキーをしたいオブジェクトを配列に変換すると奇妙な結果が出る

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

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

今、奇妙なことが出力されます:私は、次のコードを使用しています。

メンバー名をクラス名なしで(および*を付けずに)配列キーに変換する方法を誰にでも教えてください。その他のソリューションも歓迎します。

+0

ありますprint_r'は配列に情報を表示します。 –

+0

print_rは、2番目のパラメータtrueを渡すと、結果をstd Outputに送信するのではなく、結果を返します。 –

答えて

3

特殊機能が 'は、主な問題はprint_r` `におけるOPの使用` true`をとして、 `print_r`ある

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> 

demo

+0

はい、これは他のオプションです。 –