Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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']"));
share|improve this question
    
Might as well just make $array_data public if you're just going to have a public accessor method anyway. –  Supericy Jul 6 at 1:02
    
@Supericy, In my application i need to access this data via method –  Marcio Simao Jul 6 at 1:07
    
possible duplicate of PHP dynamic array index name –  buff Jul 6 at 1:18

1 Answer 1

up vote 2 down vote accepted

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'])
share|improve this answer
    
Works perfectly! Many thanks! –  Marcio Simao Jul 6 at 1:40

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.