从数组对象属性动态获取值的PHP方法


PHP method to get values dynamically from an array object property

在这个类中,是否可以从数组中动态获取值?

class MyClass {
    private $array_data;
    function __construct() {
        $this->array_data['first']['a'] = '1';
        $this->array_data['second']['b'] = '2';
        $this->array_data['third']['c'] = '3';
    }
    public function getIndexValue($index){
        return $this->{'array_data' . $index};
    }
}
$MyClass = new MyClass();
// Prints NULL, but i expect '1'
var_dump($MyClass->getIndexValue("['first']['a']"));

这里有一个简单的解决方案。不是为索引传递字符串,而是传递一个数组。

public function getIndexValue(array $indexes) {
    // count the # of indexes we have
    $count = count($indexes);
    // local reference to data
    $data = $this->array_data;
    for ($i = 0; $i < $count; $i++)
    {
        // enter the array at the current index
        $data = $data[$indexes[$i]];
    }
    return $data;
}

然后传递一个数组而不是字符串:

$MyClass->getIndexValue(['first', 'a'])