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