Page 1 of 1

not quite variable variables

Posted: Mon Mar 29, 2004 6:01 pm
by Unipus
I want to pass the name of a variable in a function, then have that refer to an array variable and make some totally awesome happenings happen. A pseudo-example:

Code: Select all

function get_loaded($type)
{
$how_many = count($type);
die($how_many);
}
$how_many never gets a value.

Several valid examples for $type are already set before this function is set. So for instance, if I call get_loaded("widgets"), I want to count the array values in $widget, already set:

Code: Select all

$widget["floaty"] = "magnificent floaty";
$widget["smackbox"] = "this sure is content.";
$widget["dracula"] = "hanging from the ceiling";
variable variables are not the answer I once dreamed they were, and concating doesn't seem to do the trick either.

Posted: Mon Mar 29, 2004 6:11 pm
by markl999
Example.

Code: Select all

<?php

function get_loaded($type)
{
  global $$type;
  $how_many = count($$type);
  die("$how_many");
}

$widgets = array();
$widgets[] = 'one';
$widgets[] = 'two';
get_loaded('widgets');

?>
So variable variables are the answer, but die($how_many) wasn't ;)
As $how_many is an integer value, the die() will be given an int, so it will treat it as an exit code. You need to have $how_many be treated as a string for die() to display it, hence the quotes in die("$how_many");

Posted: Mon Mar 29, 2004 6:28 pm
by Unipus
Gotcha. I see now.

The only thing I don't entirely get is why is global $$type necessary? $type is passed to the function by definition... so I don't get that.

Posted: Mon Mar 29, 2004 6:32 pm
by markl999
$type is just the name of the variable. To bring the actual variable into scope you need global $$type

But it does raise the question of why you don't just pass the actual variable in, or even just use count() .. ie no function required, but i'm guessing this is just a test that will have some other use ?

[edit] Never mind, i just saw the 'pseudo-example' bit ;)

Posted: Mon Mar 29, 2004 6:54 pm
by Unipus
much thanks.

Posted: Mon Mar 29, 2004 7:10 pm
by m3mn0n
markl999 wrote:But it does raise the question of why you don't just pass the actual variable in, or even just use count() .. ie no function required
My thoughts exactaly.