Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

PHP Build a Basic PHP Website (2018) Listing and Sorting Inventory Items Working with Functions

Parvez Noor
PLUS
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
210,472 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.