Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialJason S
16,247 PointsHow do I set the string of $func to be the actual function name?
So if we have this line:
function add_up($a, $b) {
return $a + $b;
}
$func = 'add_up';
is there a way to make the variable $func to be the string add up instead of the the function itself?
2 Answers
Christian Andersson
8,712 PointsI'm not too sure what you are trying to achieve here, but what you have done in the code above will give the variable $func
the String value add_up
. So if you do this:
function add_up($a, $b) {
return $a + $b;
}
$func = 'add_up';
echo $func;
you will have the following output:
add_up
Is this what you wanted to know?
Antonio Jaramillo
15,604 PointsI know this is late, but here goes nothing:
With $func = 'add_up', if you echo $func, then the string 'add_up' displays in your browser. However, if you echo $func(2, 4), then you get 6. Further if you echo $func(), you'll get an error because you haven't passed in values for $a and $b.
Jason S
16,247 PointsJason S
16,247 Pointsif i echo $func(2,4) the output would be 6. I guess a better example would be without the parameters $a, and $b.
so here the output would be 5, but what if i want the output to be the string 'add_up'?
Never mind i realized i just had to put braces around $func thank you
Christian Andersson
8,712 PointsChristian Andersson
8,712 PointsYou need to differentiate variables from functions. Variables always start with the
$
-sign. Functions never have that sign and will always have the parenthesis at the end.So the syntax
$func(x,y)
is incorrect.$func
contains the string "add_up", andfunc()
is the function name. Be aware of those dollar-signs :)Jason S
16,247 PointsJason S
16,247 Pointsactually i thought $func contains the function add_up? that's what it says in the video. and i am able to echo $func() and it will return 5 for the 2nd example, or if i echo $func(2,4) for the first will give me 2+4 which is 6