Page 1 of 1

Variable Variable Woes

Posted: Wed Mar 28, 2007 5:37 pm
by daedalus__
Consider this snippet while assuming those classes have been defined.

Code: Select all

$Test = new Test();
$Test->TestSub = new TestSub();
$Test->TestSub->TestSubSub = new TestSubSub();
printf_r($Test);

$var1 = 'Test';
$var2 = 'TestSub';
$var3 = 'TestSubSub';

$args = '';
$varvar = "namespace->$var2";
$namespace = new $var1();
${'namespace'}->{$var2} = new $var2();
${$varvar}->{$var3} = new $var3(vprintf('%s', $args));
printf_r($namespace);
echo "\${$varvar}->{$var3}";

printf_r($namespace);
Here's the output:

Code: Select all

Test Object
(
    [TestSub] => TestSub Object
        (
            [TestSubSub] => TestSubSub Object
                (
                )

        )

)

Test Object
(
    [TestSub] => TestSub Object
        (
        )

)

$namespace->TestSub->TestSubSub
It didn't throw any errors but

Code: Select all

${$varvar}->{$var3} = new $var3(vprintf('%s', $args));
did not instantiate anything.

Perhaps I am not seeing something obvious but I do not understand.......

Posted: Wed Mar 28, 2007 6:17 pm
by volka
${"namespace->xyz"} references a variable with the name namespace->xyz, not a property xyz of a variable named namespace

for illustration

Code: Select all

<?php
$var2 = 'xyz';
$varvar = "namespace->$var2";
${$varvar}  = 4711;

echo $GLOBALS['namespace->xyz'];

Posted: Wed Mar 28, 2007 6:45 pm
by daedalus__
I'm trying really hard to avoid using eval(). lol

I need to break that string up and make it usable somehow. If I figure it out, I'll post the code.

Posted: Wed Mar 28, 2007 6:54 pm
by daedalus__
Is there a way to use list() without knowing the amount of keys in the array?

Posted: Thu Mar 29, 2007 5:43 am
by Sarke
daedalus__ wrote:Is there a way to use list() without knowing the amount of keys in the array?
extract() maybe?

Code: Select all

<?php

$array['a'] = 1;
$array['b'] = 1;

extract($array);

echo $a + $b; // 2

?>

Posted: Thu Mar 29, 2007 9:37 am
by feyd

Code: Select all

<?php

$indepth = array('test','foo','bar');

$z = array_shift($indepth);
$$z = new stdClass();
for ($x = 0, $j = count($indepth); $x < $j; ++$x)
{
	$v =& $$z;
	for ($y = 0; $y < $x; ++$y)
	{
		$v =& $v->{$indepth[$y]};
	}
	$v->{$indepth[$y]} = new stdClass();
}

print_r($$z);

var_dump(phpversion());

?>
outputs

Code: Select all

stdClass Object
(
    [foo] => stdClass Object
        (
            [bar] => stdClass Object
                (
                )

        )

)
string(5) "5.1.5"
It should be simple to adapt to PHP 4.

Posted: Thu Mar 29, 2007 10:35 am
by daedalus__
I actually always have the most current version of PHP.

It's interesting that you posted that code because by the time I was going to sleep last night, the code I was working on was looking awfully similar. haha

Thanks, feyd, volka, and Sarke.