简体   繁体   English

php:动态访问数组中的元素,即object属性

[英]php: dynamically access an element in array, which is object property

i have an array as object property, $obj->_image = ['size' => '10']; 我有一个数组作为对象属性, $ 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.) 并且想要动态地访问它,例如:(当然对象已初始化并存在,只是跳过以使帖子更短.print $ obj - > _ image ['size']的工作原理应该如此。)

$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'] 但得到:未定义的属性: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] 你的代码的问题是你的属性是一个数组,所以你首先需要访问数组$this->{"_$prop"}然后是数组中的元素$this->{"_$prop"}[$el]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM