創建private功能這就是static - 即調用無它的父類的實例,並在$記錄通過
private static function instantiate($record) {
通過每個
$object = new self;
循環創建當前類的新實例$ record,將其視爲數組,其中鍵爲$屬性且值爲$ value
foreach ($record as $attribute=>$value) {
如果$對象從兩行以前的實例已經具有稱爲屬性「無論$屬性爲」
if($object->has_attribute($attribute)) {
組中的對象$對象$值的屬性值;
$object->$attribute = $value;
}
}
發送創建$對象對象返回給調用此函數
return $object;
}
創建一個私有函數的東西,所謂的「具有屬性」的結果,並傳遞一個變量$屬性爲TI
private function has_attribute($attribute) {
使用get_object_vars函數來獲取包含所有此類的當前實例的屬性的關聯數組
$object_vars = get_object_vars($this);
檢查,如果$屬性是$ object_vars使用array_key_exists,並返回結果
return array_key_exists($attribute, $object_vars);
}
你問起has_attribute功能,你可以像這樣結合在一起的:
private static function instantiate($record) {
$object = new self;
foreach ($record as $attribute=>$value) {
// eg $attribute is colour and $value is green
// read this bit as 'if $attribute is also a key in the array returned
// from "get_object_vars($this)"'
// eg if colour is a key in the array returned from 'get_object_vars($object)'
if(array_key_exists($attribute, get_object_vars($object))) {
// then set the value of $attribute in the object to be $value
// eg set the value of $object->colour to 'green'
$object->$attribute = $value;
}
}
return $object;
}
每該數組的鍵被表示爲具有相同名稱的屬性,因此賦值給它 – 2014-10-04 22:52:02
有更簡單的方法來做到這一點.. http://stackoverflow.com/questions/1869091/convert-array-to-object- php – Cheery 2014-10-04 22:54:06
我添加了一個答案,因爲你的問題是'有人可以解釋這個代碼',雖然我同意上面的@Cheery - 有很多更好的方法來做到這一點 – Jonathan 2014-10-04 23:07:27