PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
Moderator: General Moderators
phpBuddy
Forum Commoner
Posts: 37 Joined: Mon Nov 05, 2007 3:42 am
Post
by phpBuddy » Sun Nov 11, 2007 4:02 am
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.comWhat I want:
Code: Select all
// test1
name - john
age - 20
//test2
user - scoobydoo
mail - scobbydoo@hotmail.comThanks!
Last edited by
phpBuddy on Sun Nov 11, 2007 9:41 am, edited 1 time in total.
feyd
Neighborhood Spidermoddy
Posts: 31559 Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA
Post
by feyd » Sun Nov 11, 2007 8:33 am
Not without digging into the
debug_backtrace() data. It's not recommended.
phpBuddy
Forum Commoner
Posts: 37 Joined: Mon Nov 05, 2007 3:42 am
Post
by phpBuddy » Sun Nov 11, 2007 9:40 am
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 )
Zoxive
Forum Regular
Posts: 974 Joined: Fri Apr 01, 2005 4:37 pm
Location: Bay City, Michigan
Post
by Zoxive » Sun Nov 11, 2007 10:06 am
Why not use associative arrays?
Code: Select all
$Data = array(
'Name' => 'Joe',
'Job' => 'None',
);
phpBuddy
Forum Commoner
Posts: 37 Joined: Mon Nov 05, 2007 3:42 am
Post
by phpBuddy » Sun Nov 11, 2007 10:11 am
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
*/
?>