Page 1 of 1
Naming variables with variables
Posted: Sat Apr 29, 2006 3:45 am
by Paul1893
I want to be able to name my variables with other variables like iterating through $var_1, $var_2, $var_3...
What I want to do is more complicated, and more useful, than the fallowing code but if I can accomplish the following then I'll be set.
$num=1;
do {
$var_$num=$num
$num++
} while ($num<5);
$num=1;
do {
echo $var_$num;
} while ($num<5);
I need to cycle through $var_1, $var_2, $var_3...
Posted: Sat Apr 29, 2006 3:48 am
by Chris Corbyn
Generally when I see people doing this I come to the conclusion that it would be more sensible to use an array but in any case the syntax you're looking for is:
Code: Select all
$varname = 'foo';
${'prefix_'.$varname} = 42;
echo $prefix_foo;
Posted: Sat Apr 29, 2006 4:30 am
by Ollie Saunders
wow d11wtq you just tought me a new syntax, I thought I knew all of those.
This is the other method you can use:
Code: Select all
$varName = 'foo';
$extended = 'prefix_' . $varName;
$$extended = 42;
echo $prefix_foo; // outputs 42
echo $$extended; // outputs 42
echo $extended; // outputs prefex_foo
Posted: Sat Apr 29, 2006 4:56 am
by Chris Corbyn
ole wrote:wow d11wtq you just tought me a new syntax, I thought I knew all of those.
This is the other method you can use:
Code: Select all
$varName = 'foo';
$extended = 'prefix_' . $varName;
$$extended = 42;
echo $prefix_foo; // outputs 42
echo $$extended; // outputs 42
echo $extended; // outputs prefex_foo
Heh

You can do the same with function names:
Code: Select all
function something_foo()
{
}
$func = 'foo';
{'something_'.$func}();
I think that's right... doesn't look quite right though

Posted: Sat Apr 29, 2006 6:24 am
by Ollie Saunders
wow d11wtq you just tought me a new syntax, I thought I knew all of those.
Second thoughts. It doesn't actually appear to work:
Fatal error: fatal flex scanner internal error--end of buffer missed in
C:\osis\temp2.php on line
11
Posted: Sat Apr 29, 2006 6:30 am
by timvw
It's all written down in the section on variable variables in the php manual..
The following does work (i'll be honest, i don't know where this is documented)
Code: Select all
<?php
ini_set('error_reporting', E_ALL);
ini_set('display_errors', TRUE);
function foo1() {
echo 'foo';
}
$a = 1;
$func = 'foo' . $a;
$func();
?>