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!

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 Build a Basic PHP Website (2018) Listing and Sorting Inventory Items Working with Functions

Parvez Noor
Parvez Noor
Courses Plus Student 15,917 Points

Why does y = 5?

The question asked what y =. I chose 5 because the parameters in the function sum_two_numbers when setting the y variable are 2,3.

Does this mean that because the y variable is called later than when the x variable is defined, that within the function, x becomes 2 and y becomes 3, and therefore y becomes the return of z (which is 5) because y = the output of the function?

What confuses me about this, though, is doesn't mean that mean in the function y=5 and x=1? wouldn't that make it 6??

It's a little confusing!

$x = 1;

function sum_two_numbers($x,$y) { $z = $x + $y; return $z; }

$y = sum_two_numbers(2,3); echo $y;

1 Answer

Steven Parker
Steven Parker
227,114 Points

The important thing to remember for this question is the rules of variable scope. The $x and $y inside the function are totally different from the ones outside the function.

Inside the function, you were right the first time in that $x is 2 and $y is 3; because they were passed as arguments. And arguments "shadow" (take precedence over) any globals of the same name.

But outside the function, $x is still 1 and $y gets assigned to return value from the function. And those two are never added together.