Re: Can i take the variable name in a function?

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On Wed, October 11, 2006 9:58 am, Jônata Tyska Carvalho wrote:
> How can i take the variable name inside a function, ex:
>
> definition:
> function example( $ex ){
>    echo "Variable Name is $ex ";  // how to do this?
> }
>
> use:
>
> example($ball);
>
> output: Variable Name is ball;
>
> another:
>
> example($sportCar);
>
> output: Variable Name is sportCar;
>
> is that possible?

Not really.

Its local name is not all that interesting/useful anyway.

Most beginners who go down this path are taking something simple and
turning it 90 degrees on its head and making it all complicated...

What are you really trying to do, and why?

If you really really really know what you are doing, you can do this:

function example($name){
  global $name;

  echo "The variable $name has the value: ", $$name;
}

Read http://php.net section about "Variable variables" for more info.

Note that using $$variable is almost always an indication of a
mis-guided attempt to do something else, and is very likely to open up
security implications, plus usually involves using 'global' which
makes debugging/maintenance a nightmare.

The usual answer, once we find out what the programmer is REALLY
trying to do, is:

Usa an array!

function example($values){
  foreach($values as $name => $value){
    echo "$name: $value<br />\n";
  }
}

example(array('sportsCar'=>'Mazzeratti'));

Apologies in advance for probably mis-spelling the only sports car
name I could think of...

-- 
Some people have a "gift" link here.
Know what I want?
I want you to buy a CD from some starving artist.
http://cdbaby.com/browse/from/lynch
Yeah, I get a buck. So?

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux