Forum Moderators: coopster

Message Too Old, No Replies

Variables scope and variable variables

         

le_gber

11:35 am on Feb 22, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi there,

I have a function that uses variable variables which are defined outside the function.
I can't get it to work. I wondered if it even possible.

ex.

<?php

$a_foo = 'foo_not_bar';
$a_bar= 'bar_not_foo';
...

function showFooBar($which){
//$which here is of value foo or bar but in my case there's 250 values

$whichFooBar = '$a_'.$which

if(isset($$whichFooBar)) && ($$whichFooBar == 'foo')){
do something...
}

}

?>

it's the part in red I have trouble with - ie. accessing a variable variable's value oustide of the function scope.

I tried adding global $$whichFooBar but that doesn't seem to work either.

le_gber

12:14 pm on Feb 22, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



got it working thanks to WebmasterWorld once again :) - [webmasterworld.com...]

I shouldn't have use the $ sign in my new var declaration

$whichFooBar = '$a_'.$which;
becomes
$whichFooBar = 'a_'.$which;

coopster

12:25 pm on Feb 22, 2007 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Nice catch. That was the first thing I noticed. I was also going to mention that you can always use the $GLOBALS superglobal too. Example:
$a_foo = 'foo_not_bar'; 
$a_bar = 'bar_not_foo';
function showFooBar($which)
{
//$which here is of value foo or bar but in my case there's 250 values
$whichFooBar = 'a_' . $which;
// print '<pre>'; print_r($GLOBALS); print '</pre>';
if (isset($GLOBALS[$whichFooBar]) && ($GLOBALS[$whichFooBar] == 'foo')) {
print $GLOBALS[$whichFooBar];
}
}
$a_foo_not_bar = 'foo';
showFooBar('foo_not_bar');

le_gber

9:52 pm on Feb 22, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



thanks coopster - it works great