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 trial

PHP PHP Functions Function Returns and More PHP Variable Functions

Jason S
Jason S
16,247 Points

How 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

I'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?

Jason S
Jason S
16,247 Points

if i echo $func(2,4) the output would be 6. I guess a better example would be without the parameters $a, and $b.

function add_up() {
    return 5;
}
$func = 'add_up';
echo $func;

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

You 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", and func() is the function name. Be aware of those dollar-signs :)

Jason S
Jason S
16,247 Points

actually 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

I 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.