php magic method __set
I'm trying to set an ambiguous variable on a class. Something along these lines:
<?php
class MyClass {
public $values;
function __get($key){
return $this->values[$key];
}开发者_运维知识库
function __set($key, $value){
$this->values[$key]=$value;
}
}
$user= new MyClass();
$myvar = "Foo";
$user[$myvar] = "Bar";
?>
Is there a way of doing this?
As has been stated $instance->$property
(or $instance->{$property}
to make it jump out)
If you really want to access it as an array index, implement the ArrayAccess
interface and use offsetGet()
, offsetSet()
, etc.
class MyClass implements ArrayAccess{
private $_data = array();
public function offsetGet($key){
return $this->_data[$key];
}
public function offsetSet($key, $value){
$this->_data[$key] = $value;
}
// other required methods
}
$obj = new MyClass;
$obj['foo'] = 'bar';
echo $obj['foo']; // bar
Caveat: You cannot declare offsetGet
to return by reference. __get()
, however, can be which permits nested array element access of the $_data
property, for both reading and writing.
class MyClass{
private $_data = array();
public function &__get($key){
return $this->_data[$key];
}
}
$obj = new MyClass;
$obj->foo['bar']['baz'] = 'hello world';
echo $obj->foo['bar']['baz']; // hello world
print_r($obj);
/* dumps
MyClass Object
(
[_data:MyClass:private] => Array
(
[foo] => Array
(
[bar] => Array
(
[baz] => hello world
)
)
)
)
Like so: http://ideone.com/gYftr
You'd use:
$instance->$dynamicName
You access member variables with the -> operator.
$user->$myvar = "Bar";
精彩评论