Page 1 of 1

variably named functions...

Posted: Thu Nov 09, 2006 6:28 pm
by Dave2000
how might i get something similar to this to work...

Code: Select all

$variable = 'attack';

$new_gold = $old_gold + cost_$variable_gold(2);
I want to call a function depending on the value of $variable

How can i get this to work. It is just giving me the error...
Parse error: syntax error, unexpected T_VARIABLE in
Thank you

Shears :)

Posted: Thu Nov 09, 2006 7:27 pm
by RobertGonzalez
Not certain about this, but it can't hurt to try it.

Code: Select all

<?php
$variable = 'attack';
$function = cost' . $variable . 'gold';

$new_gold = $old_gold + $function(2);
?>

Posted: Thu Nov 09, 2006 8:55 pm
by Cameri
Everah wrote:Not certain about this, but it can't hurt to try it.

Code: Select all

<?php
$variable = 'attack';
$function = cost' . $variable . 'gold';

$new_gold = $old_gold + $function(2);
?>

Code: Select all

<?php
$variable = 'attack';
$function = 'cost_' . $variable . '_gold';

$new_gold = $old_gold + $function(2);
?>

Posted: Thu Nov 09, 2006 9:25 pm
by wyrmmage
yep, that's pretty much how you do it...you could always google 'variable composing' to see examples of this using variables also.
-wyrmmage

Posted: Fri Nov 10, 2006 3:54 pm
by Dave2000
Thank you. Problem solved :)

Posted: Fri Nov 10, 2006 4:04 pm
by bokehman
You'd need to eval() it.

Posted: Fri Nov 10, 2006 4:07 pm
by feyd
bokehman wrote:You'd need to eval() it.
Most often no, you don't. Unless you're talking about something else or I missed something in the thread.

Posted: Fri Nov 10, 2006 4:35 pm
by bokehman
feyd wrote:Unless you're talking about something else or I missed something in the thread.
It's quite possible I don't understand the question. I'm looking at this:

Code: Select all

$new_gold = $old_gold.'cost_'.$variable_gold.'(2);';
To get that to fire it would need to be evaled, wouldn't it? Anyway that's what I meant.

Posted: Fri Nov 10, 2006 4:48 pm
by feyd
bokehman wrote:

Code: Select all

$new_gold = $old_gold.'cost_'.$variable_gold.'(2);';
To get that to fire it would need to be evaled, wouldn't it? Anyway that's what I meant.
The way it is written in your snippet, yes it would need eval() however it could easily be adjusted to not need it at all.

Code: Select all

$func = $old_gold.'cost_'.$variable_gold; $new_gold = $func(2);

Posted: Sat Nov 11, 2006 5:35 am
by bokehman

Code: Select all

<?php

function foo($in)
{
	return $in*$in;
}

$func = 'foo';

echo $func(2);

?>
Thanks for clarifying that; I didn't know that construction existed.

Posted: Sat Nov 11, 2006 7:57 am
by RobertGonzalez
Me either, until a couple of weeks ago. I remember asking the poster 'What are you trying to do with that bit of code?' Volka then showed me the light.

Posted: Sat Nov 11, 2006 11:01 am
by wyrmmage
wow...that is quite interesting code; thanks for posting it :)