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 PHP Functions Introducing Functions Introducing Functions

What 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

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

By 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:

<?php
$a = 5;

function maybeAChange () {
  $a = "friend";
  return "$a inside the function<br>";
}

echo maybeAChange();
echo "$a outside the function";
?>

And then here is the same example, except where the $a variable is imported from the global scope:

<?php
$a = 5;

function maybeAChange () {
  global $a;
  $a = "friend";
  return "$a inside the function<br>";
}

echo maybeAChange();
echo "$a outside the function";
?>

Why does the teacher have to write the current user variable outside the function? Why not write it inside the function?

Hey Marcus

You hero! Thanks so much, very handy and I get it now. Fingers crossed I can pay it forwards soon.

Cheers

Mike

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

Sorry, new to this and thought I had, but clearly I unselected it again! Done now- cheers.

It's no biggie to me at all, and I'm just glad I could help. Happy Coding!