簡體   English   中英

從關聯數組創建php類對象

[英]creating php class object from associative array

我正在開發一個可以在模型中包含自定義字段的軟件。 這意味着客戶可以使用用戶界面添加和刪除字段。

現在,我有一個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;

這是正確的嗎?

謝謝

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

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

希望它能對您有所幫助:)

如果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" 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM