tags:

views:

42

answers:

4

Hello,

I tried to access with $this->$arrDataName[$key] on the element with the key $key from the array $this->$arrDataName. But PHP interpretes that wrong.

I tried it with { } around the $arrDataName to $this->{$arrDataName}[$key], but it doesn't work.

On php.net I found an advice, but I can't realize it.

In order to use variable variables with arrays, you have to resolve an ambiguity problem. That is, if you write $$a[1] then the parser needs to know if you meant to use $a[1] as a variable, or if you wanted $$a as the variable and then the [1] index from that variable. The syntax for resolving this ambiguity is: ${$a[1]} for the first case and ${$a}[1] for the second.

Perhaps anyone can help me.

Thanks!

EDIT:

I think it doesn't work, but I forgot to fill the array.
Finally it works. :)
This is the solution: $this->{$arrDataName}[$key]

+1  A: 

Your syntax is correct:

$this->{$varName}[$key]

You can also use an extra variable for this:

$myTempArr = $this->$arrDataName;

$myTempArr[ $key ];

IMHO, readability is better that way...

Macmade
Thanks for the advice.I know that way, but I search for the one line solution. ;)
H3llGhost
I just tested the syntax, and it's correct. Maybe you've got another problem...
Macmade
I found my problem.The specified array was empty. -.-
H3llGhost
A: 

Let's assume your array is $this->arrDataName. You have a $key, so your object would be $this->arrDataName[$key].

If you want the contents of the variable which name is stored in $this->arrDataName[$key] you should do this:

<?php
    echo ${$this->arrDataName[$key]};
?>
Bogdan Constantinescu
Sorry, but I can't figure out, how that will help me.
H3llGhost
A: 

Well, as far as I know, it works. Here how I tested it:

<?php
class tis
{
    var $a = array('a', 'b', 'c');
    var $b = array('x', 'y', 'z');

    public function read($var)
    {
        echo $this->{$var}[1].'<br />';
    }
}

$t = new tis();
$t->read('a');
$t->read('b');
?>

And the output:

b
y

Check correctness of $arrDataName. Turn on debuging and displaying PHP erros (including notices). Maybe you're trying to read non-existing property?

Also, which PHP version you use? I assume PHP5?

Tomasz Struczyński
...and a comment - if possible, it's better not to use this magic. Later on, you'll have problems understanding what you wanted to do. Believe me :)
Tomasz Struczyński
I use PHP 5.3.1 and there aren't any errors or notices.
H3llGhost
@H3llGhost: You have set `error_reporting` to `E_ALL | E_STRICT`? And `display_errors` is enabled?
nikic
Yes. The typical options for developing. ;) I had a board in front of my head.
H3llGhost
+1  A: 
<?php
    class Foo {
        public function __construct() {
            $this->myArray = array('FooBar');
            $arrayName = 'myArray';
            echo $this->{$arrayName}[0];
        }
    }
    new Foo;

This worked perfectly for me, it printed FooBar.

nikic
Yes it worked for me too. ;)Thanks.
H3llGhost