0

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

1 Answer 1

3

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'])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.