2

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.

2
  • the main problem is print_r, as the OP use true in print_r, the print_r display the information with the array. Commented May 19, 2016 at 8:51
  • print_r will return the result instead of sending it to std Output when you pass second parameter true, that why I have added true. Commented May 19, 2016 at 10:54

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.