Marcio Mazzucato
Marcio Mazzucato

Reputation: 9305

PHP method to get values dynamically from an array object property

In this class, is it possible to get dynamically a value from the array?

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

Upvotes: 0

Views: 1728

Answers (1)

Supericy
Supericy

Reputation: 5896

Here's a simple solution. Rather than passing in a string for the indexes, you pass in an array.

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;
}

And then rather than a string, you'd pass in an array:

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

Upvotes: 3

Related Questions