2

I have a function that returns the value of a variable inside an object like so :

public function getVar($var)
{
    return ($this->$var);
} 

It works fine, but I cannot find a way to get the value of an array stored inside a variable. I thought something like this would work:

$object->getVar("variable['value']");

but it doesn't .... How can I do that ?

1 Answer 1

1

This syntax is not applicable to arrays. Use this instead:

public function getVar($var, $index = null)
{
    if (null === $index)
        return $this->$var;

    $var = $this->$var;
    return $var[$index];
}

Usage:

$yourClass = new YourClass();

$yourClass->array = array('a' => 'b');
$yourClass->someVar = 'c';

echo $yourClass->getVar('array', 'a'); // output: b
echo $yourClass->getVar('someVar'); // output: c
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.