Метод PHP для динамического получения значений из свойства объекта массива - программирование

Метод PHP для динамического получения значений из свойства объекта массива

В этом классе можно ли динамически получить значение из массива?

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']"));
4b9b3361

Ответ 1

Здесь простое решение. Вместо того, чтобы передавать строку для индексов, вы передаете массив.

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'])