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();