从关联数组创建php类对象

时间:2016-02-29 13:50:09

标签: php arrays object

我正在开发一个模型可以拥有自定义字段的软件。这意味着使用用户界面,客户可以添加和删除字段。

现在,我有一个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 个答案:

答案 0 :(得分:2)

您可以使用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);

希望它会对你有所帮助:)。

答案 1 :(得分:2)

如果getCustomer()函数用作生成Customer类对象的全局函数,请使用以下方法:

  • Customer课程中封装所有传递的客户数据。 标记&#34; main&#34;属性为private
  • 声明将负责的setCustomerData()方法 设置所有客户的属性
  • 使用特权方法来获取&#34;获取&#34;来自客户端代码的那些属性

    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" 
    
相关问题