Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Convert object to array

When a object with private variables, has converted (cast) to an array in php the array element keys will be started with

*_

. How to remove the "*_"s that exists at the beginning of array keys?

For example

class Book {
    private $_name;
    private $_price;
}

the array after casting

array('*_name' => 'abc', '*_price' => '100')

I want

array('name' => 'abc', 'price' => '100')
like image 771
Sachindra Avatar asked Jun 07 '12 09:06

Sachindra


2 Answers

I did it in this way

class Book {
    private $_name;
    private $_price;

    public function toArray() {
        $vars = get_object_vars ( $this );
        $array = array ();
        foreach ( $vars as $key => $value ) {
            $array [ltrim ( $key, '_' )] = $value;
        }
        return $array;
    }
}

and when I want to convert a book object to an array I call the toArray() function

$book->toArray();
like image 57
Sachindra Avatar answered Sep 22 '22 15:09

Sachindra


to do this properly you need to implement a toArray() method in your class. That way you can keep your properties protected and still have access to the array of properties.
There are many ways to accomplish this, here is one method useful if you pass the object data to the constructor as an array.

//pass an array to constructor
public function __construct(array $options = NULL) {
        //if we pass an array to the constructor
        if (is_array($options)) {
            //call setOptions() and pass the array
            $this->setOptions($options);
        }
    }

    public function setOptions(array $options) {
        //an array of getters and setters
        $methods = get_class_methods($this);
        //loop through the options array and call setters
        foreach ($options as $key => $value) {
            //here we build an array of values as we set properties.
            $this->_data[$key] = $value;
            $method = 'set' . ucfirst($key);
            if (in_array($method, $methods)) {
                $this->$method($value);
            }
        }
        return $this;
    }

//just return the array we built in setOptions
public function toArray() {

        return $this->_data;
    }

you can also build an array using your getters and code to make the array look how you want. Also you can use __set() and __get() to make this work as well.

when all is said and done the goal would be to have something that works like:

//instantiate an object
$book = new Book(array($values);
//turn object into an array
$array = $book->toArray();
like image 38
RockyFord Avatar answered Sep 24 '22 15:09

RockyFord