PHP—像使用数组一样使用对象
class Person implements ArrayAccess{
private $attributes = array();
/**
* @param $attribute
* @return null
*/
public function __get($attribute)
{
if (isset($this->{$attribute})) {
return $this->$attribute;
} else if (isset($this->attributes[$attribute])) {
return $this->attributes[$attribute];
} else {
return null;
}
}
/**
* @param $attribute
* @param $value
*/
public function __set($attribute, $value)
{
$this->{$attribute} = $value;
}
/**
* @param mixed $offset
* @return mixed
*/
public function offsetGet($offset)
{
return $this->attributes[$offset];
}
/**
* @param mixed $offset
* @param mixed $value
*/
public function offsetSet($offset, $value)
{
$this->attributes[$offset] = $value;
}
/**
* @param mixed $offset
*/
public function offsetUnset($offset)
{
if (isset($this->attributes[$offset])) {
unset($this->attributes[$offset]);
}
}
/**
* @param mixed $offset
* @return bool
*/
public function offsetExists($offset)
{
return isset($this->attributes[$offset]);
}
}
$person = new Person();
$person['name'] = 'fatrbaby';
$person['age'] = 18;
echo $person['name'], '', $person['age'];
echo '';
echo $person->name, '', $person->age;
页:
[1]