这个简单的代码应该可以工作:
class MyClass {
public function __construct(Array $properties=array()){
foreach($properties as $key => $value){
$this->{$key} = $value;
}
}
}
?>
使用示例
$foo = new MyClass(array("hello" => "world"));
$foo->hello // => "world"
或者,这可能是一个更好的方法
class MyClass {
private $_data;
public function __construct(Array $properties=array()){
$this->_data = $properties;
}
// magic methods!
public function __set($property, $value){
return $this->_data[$property] = $value;
}
public function __get($property){
return array_key_exists($property, $this->_data)
? $this->_data[$property]
: null
;
}
}
?>
用法是一样的
// init
$foo = new MyClass(array("hello" => "world"));
$foo->hello; // => "world"
// set: this calls __set()
$foo->invader = "zim";
// get: this calls __get()
$foo->invader; // => "zim"
// attempt to get a data[key] that isn't set
$foo->invalid; // => null