Page 1 of 1
Pass argument variable name to function? [resolved]
Posted: Sun Nov 11, 2007 4:02 am
by phpBuddy
Code: Select all
<?php
function echo_variable(){
$args = func_get_args();
foreach($args AS $key => $val)
echo $key.' - '.$val.'<br>';
}
// test 1
$name = 'john';
$age = 20;
echo_variable($name, $age);
echo '<br>';
//test 2
$user = 'scoobydoo';
$mail = 'scobbydoo@hotmail.com';
echo_variable($user, $mail);
echo '<br>';
?>
I wonder if there is some way a function can get the name of a variable
which is passed to the function as an argument.
The result of my test:
Code: Select all
// test1
0 - john
1 - 20
//test2
0 - scoobydoo
1 - scobbydoo@hotmail.com
What I want:
Code: Select all
// test1
name - john
age - 20
//test2
user - scoobydoo
mail - scobbydoo@hotmail.com
Thanks!
Posted: Sun Nov 11, 2007 8:33 am
by feyd
Not without digging into the
debug_backtrace() data. It's not recommended.
Posted: Sun Nov 11, 2007 9:40 am
by phpBuddy
feyd wrote:Not without digging into the
debug_backtrace() data. It's not recommended.
Thanks. I will mark this resolved.
I will adjust my function to be served the variable name, in another value.
Maybe like this
array ( 'name', $name )
Posted: Sun Nov 11, 2007 10:06 am
by Zoxive
Why not use associative arrays?
Code: Select all
$Data = array(
'Name' => 'Joe',
'Job' => 'None',
);
Posted: Sun Nov 11, 2007 10:11 am
by phpBuddy
Zoxive wrote:Why not use associative arrays?
Yes, this is a good idea, too.
Especially when passing more then one variable, it is better.
Code: Select all
<?php
function echo_variable($arg){
foreach($arg AS $key => $val)
echo $key.' - '.$val.'<br />';
}
// test
$name = 'John';
$age = 25;
$job ='manager';
$email = 'john_1234@hotmail.com';
$data = array(
'name' => $name,
'age' => $age,
'job' => $job,
'email'=> $email,
);
echo_variable($data);
/* Output:
name - John
age - 25
job - manager
email - john_1234@hotmail.com
*/
?>