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