PHP将关联数组转换为对象

时间:2014-10-04 22:48:28

标签: php

我已经按照PHP OOP教程将数组转换为对象

private static function instantiate($record) {
    $object = new self;
     foreach ($record as $attribute=>$value) {
         if($object->has_attribute($attribute)) {
             $object->$attribute = $value;
         }
     }
     return $object;
}

private function has_attribute($attribute) {
    $object_vars = get_object_vars($this);
    return array_key_exists($attribute, $object_vars);
}

它有效,但我不明白这个机制。有人可以为我解决这个问题,这样我就能理解它是如何工作的,还是有其他办法可以达到同样的效果?

1 个答案:

答案 0 :(得分:1)

创建一个private函数static - 即可调用而没有其父类的实例并传入$ record

private static function instantiate($record) {

创建当前类的新实例

    $object = new self;

遍历每个$记录,将其视为一个数组,其中键为$ attribute,值为$ value

     foreach ($record as $attribute=>$value) {

如果前面两行的$ object实例已经有一个名为'what $ attribute is'的属性

         if($object->has_attribute($attribute)) {

将对象$ object中的该属性设置为$ value;

的值
             $object->$attribute = $value;
         }

    }

将创建$ object对象的结果发送回调用此函数的东西

    return $object;
}

创建一个名为'has attribute'的私有函数,并将变量$ attribute传递给ti

private function has_attribute($attribute) {

使用get_object_vars函数获取一个包含该类当前实例的所有属性的关联数组

    $object_vars = get_object_vars($this);

使用array_key_exists检查$ attribute是否在$ object_vars中并返回结果

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