2016-02-29 135 views
0

我正在研究一個模型可以具有自定義字段的軟件。這意味着使用用戶界面,客戶可以添加和刪除字段。從關聯數組創建php類對象

現在,我有一個Customer類,我想從關聯數組或JSON中填充對象值。通常我會做的是:

$customer = new Customer(); 

$customer->first_name = $firstName; 
$customer->last_name = $lastName; 
..... 

我要的是能夠做到這樣的:

$data = array(
    "first_name" => $firstName, 
    "last_name" => $lastName, 
    .... 
); 

$customer = getCustomer($data); 

和GETCUSTOMER()方法不應該依賴於數組中的條目數。

這是可以在PHP中?

我發現搜索是這樣的:

$customer = (object)$data; 

它是正確的嗎?

感謝

回答

2

如果getCustomer()功能的目的是作爲一個全局函數生成Customer類的對象,請使用以下方法:

  • 封裝所有通過客戶數據在Customer類。 馬克「主」屬性private
  • 聲明setCustomerData()方法,將負責 設置所有客戶的屬性
  • 使用特權方法「獲取」從客戶端代碼的那些屬性

    function getCustomer(array $data) { 
        $customer = new Customer();  
        $customer->setCustomerData($data); 
    
        return $customer; 
    } 
    
    class Customer 
    { 
        private $first_name; 
        private $last_name; 
        // other crucial attributes 
    
        public function setCustomerData(array $data) 
        { 
         foreach ($data as $prop => $value) { 
          $this->{$prop} = $value; 
         } 
        } 
    
        public function getFirstName() 
        { 
         return $this->first_name; 
        } 
    
        // ... other privileged methods 
    
    } 
    
    $data = array(
        "first_name" => "John", 
        "last_name" => $lastName, 
        .... 
    ); 
    
    $customer = getCustomer($data); 
    echo $customer->getFirstName(); // "John" 
    
+0

你爲什麼不在構造函數中傳遞數據?還應該檢查傳入的值以確保它們被允許由用戶設置。 – miken32

+0

@ miken32,當然,在「真正的」生產計劃中,解決方案應該得到補充和調整。我認爲沒有人應該將「任意」數組傳遞給對象的構造函數。我們應該將關鍵和必需對象的屬性和依賴(服務)對象傳遞給構造函數。想象一下,在這種情況下,某人正在將包含1000個元素的數組傳遞給構造函數...但是,所需屬性列表包含20個屬性(例如) – RomanPerekhrest

+0

因此,應該考慮這樣一些問題:「客戶對象的必需屬性是什麼? 「 ,「通過任意數組的允許大小是多少?」,「我應該創建一些PersonFactory類來生成這樣的對象嗎?」 – RomanPerekhrest

2

您可以使用__set__get PHP的魔術方法。

class Customer{ 

    private $data = []; 

    function __construct($property=[]){ 
    if(!empty($property)){ 
     foreach($property as $key=>$value){ 
     $this->__set($key,$value); 
     } 
    } 
    } 

    public function __set($name, $value){ // set key and value in data property  
     $this->data[$name] = $value; 
    } 

    public function __get($name){ // get propery value 
    if(isset($this->data[$name])) { 
     return $this->data[$name]; 
    } 
    } 

    public function getData(){ 
    return $this->data; 
    } 

} 

$customer = new Customer(); 
$customer->first_name = 'A'; 
$customer->last_name = 'B'; 

// OR 

$data = array(
    "first_name" => 'A', 
    "last_name" => 'B', 
); 

$customer = new Customer($data); 
echo '<pre>'; print_r($customer->getData()); 
$res = (object)$customer->getData(); 
echo '<pre>'; print_r($res); 

希望它會幫助你:)