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 Build a Simple PHP Application Working With Functions Displaying Only Four Shirts

Viki Pattanaik
Viki Pattanaik
6,314 Points

I was taught you cannot use global variables by default insidea function without specifying globals inside the function

In the preceeding tutorial on PHP functions (the course that comes right before this one), I was specifically taught that global variables while global in scope cannot be used inside a function unless you specify them as global within the function. Now, here I see you calling two global variables outside the scope of the function and without even specifying them global using them inside. I know it works, because my code runs alright but then why was I taught that in the previous Functions course? Am I missing something here?

Cheers! Viki

3 Answers

Alven Maretinus
Alven Maretinus
5,091 Points

As I know, global variables can be used even without specifying them in the function you want to use them in. The declaration is simply about the matter of neat code, to make the code much more beautiful and readable in many ways.

Correct me if I'm wrong

you can call a variable set on a page in a function by using global or you can pass them into the function examples: function example($a,$b){ do something with $A and $b} or function example2(){ global $a $b now do something with $a and $b}

The two global variables $total_products and $position are not actually being used by the get_list_view_html() function.

This function's only job is to build the HTML for each product item.