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

Miguel Nunez
Miguel Nunez
3,266 Points

In simple terms what is a Variable Scope (global)

Is it the same as a regular variable?

3 Answers

Variable scope isn't a type of a variable. It actually describes where the variable was declared. You can think of it as a location of the variable. If a variable is defined inside a function, then it's only accessible in that function. This is known as function scope. Any variable defined outside of a function is defined in global scope. Such variables are accessible anywhere in the file, but not inside any of the functions.

Does that make sense?

Miguel Nunez
Miguel Nunez
3,266 Points

yes it does but can you give me example how that might look like you don't have to go in depth of labeling things or any thing like that just saying that will be really appreciated.

Of course. Here's an example:

<?php

$globalScopeVar = 'I am in global scope.';

function someFunction() {
    $funcScopeVar = 'I am in function scope.';

    echo $globalScopeVar;  // will not work

    echo $funcScopeVar;  // outputs 'I am in function scope.'
}

echo $globalScopeVar;  // outputs 'I am in global scope.'

echo $funcScopeVar;  // will not work
?>
Miguel Nunez
Miguel Nunez
3,266 Points

yes it does but can you give me example how that might look like you don't have to go in depth of labeling things or any thing like that just saying that will be really appreciated.