Current time: 04-18-2014, 03:36 AM Hello There, Guest! (LoginRegister)

Post Reply 
$$array individual elements
07-29-2008, 07:29 PM
Post: #1
$$array individual elements
Hi,

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...
Code:
<?php
class test() {
var $_example = array('hello' => 'Hi!');

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

$testclass = new test('_example');
?>
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...
Code:
<?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!
Find all posts by this user
Quote this message in a reply
07-29-2008, 11:08 PM
Post: #2
$$array individual elements
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.

Code:
<?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.
Find all posts by this user
Quote this message in a reply
07-31-2008, 10:26 AM
Post: #3
$$array individual elements
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
Find all posts by this user
Quote this message in a reply
Post Reply 


Forum Jump: