php设置对象属性,如array_fill_keys($ keys,'')对数组有效

时间:2013-01-14 06:24:16

标签: php object properties

我想要一个允许我设置对象属性的PHP方法,如:

array_fill_keys($keys, '');

用于数组的索引

1 个答案:

答案 0 :(得分:1)

这可能会起到作用:

// Same value for al properties, uses array values only
function object_fill_properties($properties, $value) {
    foreach ($properties as $property) {
        if (property_exists($this, $property)) {
            $this->$property = $value;
        }
    }
}

// Different values for each property, uses key-value array
function object_fill_properties_kv($properties) {
    foreach ($properties as $property => $value) {
        if (property_exists($this, $property)) {
            $this->$property = $value;
        }
    }
}

如您所见,这适用于现有属性。另一方面,如果您希望在运行时向对象添加属性,请查看this question