1

可能重复:
PHP - 使用数组参数初始化对象成员

我正在寻找一种方法让我的类将关联数组中的数据应用到它自己的成员变量中。但是,如果这些变量不存在,则该过程不应引发任何错误。

请注意:我不是在寻找 extract() 函数的作用,就是我误解了它的行为。

例子:

class customer {

    public $firstName;
    public $lastName;
    public $email;

    public function apply($data){
        /* here i want to be able to iterate through $data and set the class
           variables according to the keys, but without causing problems 
           (and without creating the variable in the class) if it does not exist
           (yet)) */
    }

}

$c=new customer();
$c->apply(array(
    'firstName' => 'Max',
    'lastName'  => 'Earthman',
    'email'     => 'max@earthman.com'
));

希望描述正确。

请询问是否有任何不清楚的地方。

4

2 回答 2

2

你可以做这样的事情

class customer {
    public $firstName;
    public $lastName;
    public $email;

    public function apply($data) {
        $var = get_class_vars(__CLASS__);
        foreach ( $data as $key => $value ) {
            if (array_key_exists($key, $var)) {
                $this->$key = $value;
            }
        }
    }
}

$c = new customer();
$c->apply(array('firstName' => 'Max','lastName' => 'Earthman','email' => 'max@earthman.com',"aaa" => "bbb"));
var_dump($c);

输出

object(customer)[1]
  public 'firstName' => string 'Max' (length=3)
  public 'lastName' => string 'Earthman' (length=8)
  public 'email' => string 'max@earthman.com' (length=16)
于 2012-10-07T16:29:09.327 回答
0
//Works for private as of 5.3.0 
//Will also return statics though.

public function apply($data){
   foreach($data  as $key => $val) {
      if(property_exists('customer',$key)) {
         $this->$key = $val;
      }
   } 
}

如果这是来自数据库,则有函数可以直接返回对象,而不必将关联的数组应用于类。只是一个想法。

于 2012-10-07T16:39:07.847 回答