php:动态访问数组中的元素,即object属性
问题描述:
i have an array as object property, $obj->_image = ['size' => '10']; and want to access it dynamically, like: (of course object initialized and exists, just skipped to make post shorter. print $obj->_image['size'] works like it should.)
$obj->get('image','size');
public function get($item,$element = '') {
if (!empty($element)) $element = "['$element']";
$item = "_$item$element";
return $this->$item;
}
but get: Undefined property: obj::$_image['size']
tryed with {}, $$ - but looks like i am missing something..
答
Your problem is that you're trying to access a property that is an array, so you can't do it like you are doing it. Try this
class a
{
private $_image = array("size" => 10);
public function get($item, $element = '')
{
$prop = "_$item";
if (property_exists(__CLASS__, $prop))
{
if (empty($element))
{
return $this->{$prop};
}
if(array_key_exists($element, $this->{$prop})){
return $this->{$prop}[$element];
}
}
throw new Exception("'$item' or '$element' don't exist");
}
}
$a = new a;
echo $a->get("image", "size");
The problem with your code is that your property is an array, so you first need to access the array $this->{"_$prop"}
and then the element within the array $this->{"_$prop"}[$el]