$$array individual elements

software development



I have a hopefully quick question for somebody more familiar with the syntax of PHP than myself.

I have a class and a function that accesses a variable named whatever value is passed in the argument like this…

class test() {
var $_example = array(‘hello’ => ‘Hi!’);

function test($var_name) {
echo $this->$var_name[‘hello’];//this line, as you can probably guess, won’t work.

$testclass = new test(’_example’);
[/code]So, the print_r() shows all of the elements of the array. But the line I commented on does not work. I have tried all kinds of variations to try and access an individual element out of this, but I can’t seem to get it. I’ve even tried concatinating the element onto the $var_name variable like this…
$var_name .= “[‘hello’]”;
…but that doesn’t work either.

If you’ve ever used a $$variablevariable, I think this works in about the same way with the $this operator, as the following will not work either…

<?php $a = array('hello' => 'Hi!'); $b = 'a'; print_r($$b);//same as print_r($a) echo $$b['hello'];//doesn't work ?> Thanks for any help on this one!


Well, I took a break and came back with this work around. I’m still really interested in how the syntax is supposed to go for the above example (so if anybody knows, please share), but this is a very easy work around and I don’t know why it never came to mind before.

<?php class test { var $_example = array('hello' => 'Hi!'); test($var_name) { $local_copy_of_the_array = $this->$var_name; echo $local_copy_of_the_array['hello'];//prints Hi! } } $testclass = new test('_example'); ?> BTW, sorry about those parenthesise on class test() I put on my first post–didn’t notice them before.


This works:

<?php $a = array('hello' => 'Hi!'); $b = 'a'; $c = $$b; print_r($$b);//same as print_r($a) echo $$b['hello'];//doesn't work echo $c[hello];// works. ?>

I tried {$$b}[‘hello’] but that didn’t work. I think there is a way to make sure the variable gets resolved before the index. Maybe my $c will work for you

Joel Goldstick