toArray()
これを適切に行うには、クラスにメソッドを実装する必要があります。こうすることで、プロパティを保護したまま、プロパティの配列にアクセスできます。
これを実現するには多くの方法があります。オブジェクト データをコンストラクターに配列として渡す場合に役立つ方法の 1 つを次に示します。
//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;
}
また、getter とコードを使用して配列を構築し、配列の外観を希望どおりにすることもできます。また、__set() と __get() を使用してこれを機能させることもできます。
結局のところ、目標は次のように機能することです。
//instantiate an object
$book = new Book(array($values);
//turn object into an array
$array = $book->toArray();