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')
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();
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With