Welcome to WebmasterWorld Guest from

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

Function Question

getting variable name and value from one argument



4:52 pm on Dec 29, 2005 (gmt 0)

10+ Year Member

I have a function that requires both the value of the field and its name. Now I'm calling it as follows, where $field is a variable defined in the script that the function is called:

my_function($field, field)

Am I stuck with needing to use both arguments, or is there any way that I can just use one argument (field), and that the function can then be structured to get the actual value of $field from the script where that value is defined?

Or is there just no way that a function can use variables that are defined in the script (other than as a function argument)?


5:11 pm on Dec 29, 2005 (gmt 0)

WebmasterWorld Administrator jatar_k is a WebmasterWorld Top Contributor of All Time 10+ Year Member

this thread from the PHP Library [webmasterworld.com] might shed some light
Understanding Custom Functions and Variable Scope in PHP [webmasterworld.com]


6:23 pm on Dec 29, 2005 (gmt 0)

10+ Year Member

Thanks those links were very helpful. I have an idea of how to do this now, but still don't know if there is a way to extract out a variable name.

For example if I have

$color= "red";

So the variable color has the value of red. Is there anyway to extract the actual variable name from $color? (I just want the 'color' part) So that I could finally have something like:

$y = "color";


7:06 pm on Dec 29, 2005 (gmt 0)

10+ Year Member

Sorry about that, I was overthinking things. I can do it with:

$y = '$color';

$y = str_replace("$", "", $y);


9:35 pm on Dec 29, 2005 (gmt 0)

10+ Year Member

Possible Plan of Action

my_function($field_name) {

$field_value = $_GLOBALS[$field_name]; // get value of field variable

// sample function action

echo '$'. $field_name .' contains the value: '. $field_value;

// end sample


Now say you have $j, that has the value 5.

The following:


Prints out:

"$j contains the value: 5"


I'm confused what the purpose is of the function, but the code above would help you get the variable value with just the variable name alone.


Featured Threads

Hot Threads This Week

Hot Threads This Month