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 trialmichaeldavies3
22,911 PointsWhat is the purpose of "global $current_user;"?
Hi
Possible a silly question, but what is the purpose of "global $current_user;" in the code in this video? I thought the variable $current_user had been defined before the function, but clearly I'm missing something here!
Thanks everyone :)
3 Answers
Marcus Parsons
15,719 PointsHey Michael,
In PHP, variables have a single scope and if they are placed outside of a function, they are considered global. If they are placed inside a function, they are considered local to that function. PHP prefers local variables to global variables unless explicitly told to otherwise do so; this is where that "global" keyword comes into play.
The reason why we have to use the keyword "global" here is that if we left off "global", we would be trying to use a local variable named $current_user that doesn't exist. So, we have to import the "$current_user" variable from the global environment to use it in our function.
To read more about this, check out this article on the PHP.net site.
michaeldavies3
22,911 PointsHey Marcus
You hero! Thanks so much, very handy and I get it now. Fingers crossed I can pay it forwards soon.
Cheers
Mike
Marcus Parsons
15,719 PointsNo problem, man! Paying it forward is what it's all about, Mike. By the way, it looks like you did select me as best answer, but then it is gone lol. It is cool if you want to wait, but if I answered your question, I do appreciate being selected as best answer.
michaeldavies3
22,911 PointsSorry, new to this and thought I had, but clearly I unselected it again! Done now- cheers.
Marcus Parsons
15,719 PointsIt's no biggie to me at all, and I'm just glad I could help. Happy Coding!
Marcus Parsons
15,719 PointsMarcus Parsons
15,719 PointsBy the way, here are some nifty examples to run. Here's one version where two exactly the same variables are used, one is declared outside the function, and one inside. Check out the values:
And then here is the same example, except where the $a variable is imported from the global scope:
web pad
4,483 Pointsweb pad
4,483 PointsWhy does the teacher have to write the current user variable outside the function? Why not write it inside the function?