Sign In | Subscribe

Enter your Sign on user name and password.

Forgot password?
  • Follow us on:
Start learning today, and be successful in your academic & professional career. Start Today!
Loading video...
This is a quick preview of the lesson. For full access, please Log In or Sign up.
For more information, please see full course syllabus of Introduction to PHP
  • Discussion

  • Study Guides

  • Download Lecture Slides

  • Table of Contents

  • Transcription

  • Related Services

Start Learning Now

Our free lessons will get you started (Adobe Flash® required).
Get immediate access to our entire library.

Sign up for

Membership Overview

  • Unlimited access to our entire library of courses.
  • Search and jump to exactly what you want to learn.
  • *Ask questions and get answers from the community and our teachers!
  • Practice questions with step-by-step solutions.
  • Download lesson files for programming and software training practice.
  • Track your course viewing progress.
  • Download lecture slides for taking notes.
  • Learn at your own pace... anytime, anywhere!

Variable Scope

  • Variable scope refers to the part of a script where a variable can be accessed.
  • Variables defined in a script outside of a function have global scope . A variable with global scope can be used anywhere within the script it is defined or the files included in the script it is defined (*except within functions).
  • Variables defined in functions, including function parameters, have what is known as local function scope . Variables with local function scope can only be accessed from within the function.
  • The global keyword allows variables with global scope to be used within functions and variables with local function scope to be used in the global scope.
  • Superglobal variables are pre-defined associative array variables that are always available in both the global scope and local function scope.
  • The $GLOBALS superglobal contains all of the variables currently in the global scope of a script. It can be used to access global variables from within local function scope.
  • All constants are accessible in both the global and local function scope.
  • Functions have global scope, meaning as long as a function is defined within a script or one of its include files, it can be called anywhere within that script or its include files.
  • Additional Resources:

Variable Scope

Lecture Slides are screen-captured images of important points in the lecture. Students can download and print out these lecture slide images to do practice problems as well as take notes while watching the lecture.

  • Intro 0:00
  • Lesson Overview 0:09
    • Lesson Overview
  • What is Variable Scope? 0:57
    • Variable Scope
    • Global Scope
    • Local Function Scope
  • Variable Scope Coding Example 2:26
    • Variable Scope Coding Example
  • global Keyword 8:52
    • global Keyword Overview
    • global Keyword Example
  • Superglobals 12:34
    • Superglobals
    • Superglobals Example
  • Pitfalls of Global Variables 18:34
    • Pitfalls of Global Variables
  • When to Define Variables 22:09
    • When to Define Variables
  • Putting It All Together 22:56
    • Putting It All Together Example
  • Function Scope 28:56
    • Function Scope
  • Homework Challenge 29:41
    • Homework Challenge
  • Homework Challenge (cont.) 30:59
    • Homework Challenge (cont.)

Transcription: Variable Scope

Hello again, and welcome back to's Introduction to PHP course.0000

In today's lesson, we are going to be talking about the concept known as variable scope.0004

Specifically, we are going to be talking about what variable scope is.0011

We are going to be talking about a special word in PHP, the global keyword.0014

We are going to go into more detail about superglobals, which is something we have mentioned0020

when we have talked about the _GET and _SERVER superglobal arrays that we have used in previous lessons.0023

We are going to talk more about actually what superglobals are.0031

We are going to talk about some of the pitfalls of using what are known as global variables.0033

We are going to talk about when variables are to be defined.0038

And then, we are going to finish up with an example that puts together all of the stuff that we have learned in the lesson,0042

and then quickly just talk about something that doesn't fall under variable scope, but is a related issue; it is called function scope.0049

What is variable scope? Well, essentially, variable scope refers to what in part of a script a variable is accessible.0058

For example, when we define a variable in our script, a=1, it is available within all of our script.0067

So far, all of the variables we have defined in our scripts are what are known as global variables, and have what is known as global scope.0075

And what that means is: once they are defined, they are able to be used anywhere within the file.0083

And they also can be used within any include files.0090

For example, on our web application, where we defined the pageTitle variable, when we include our header file,0093

it can access that pageTitle variable and use it, because it is within its scope.0100

It is a global variable, so it is available to the entire script and any of its include files.0106

However, now that we have introduced user-defined functions...variables defined in functions0111

have a different scope, what is known as local function scope.0117

And that affects the ability to use variables defined in your script within a function, and variables defined within a function within the script.0121

The reason is what is known as scoping rules.0130

Essentially, any variables that are defined within a function have local function scope, and they can only be accessed from within the function.0134

This include function parameters.0144

Let's take a look at a file called scope.php; we have a couple of functions here that we are going to get to in a second.0147

The first thing I am going to do is: in our script, we have two functions defined up here, and then we have a variable assignment statement0154

that declares a variable we are calling globalInt=25.0164

And because it is defined in our main script, as mentioned, just like all of our other variables we work with, it is a global variable.0169

So, it is accessible anywhere in the script; so when I type echo globalINT, PHP is going to know what that variable responds to.0174

That variable is going to have scope, and PHP is going to know where to find its value.0185

When I go ahead and load the page, it will output 25.0190

However, let's say (this function up here that we have created is called changeGlobalInt), for example, that we want to run this function,0197

and then change the value of this global integer from 25 to 0.0209

And that is what this function is going to do.0215

Well, 2 things to note: the first thing is that, if we go ahead and run this function, and then we echo globalInt again,0218

we are going to see that it does not get updated.0236

The reason is that globalInt is defined in the global scope (and so it has global scope),0240

but once you enter into a function, those global variables are no longer available.0246

So, even though we are referring to globalInt, which was previously defined in the script, and we are going to set it to 0,0251

this globalInt is kind of like its own separate variable; it only works within the function body.0257

And it doesn't affect this global variable defined out here.0264

This globalInt, even though it has the same name, is a local function variable..0269

So again, all we are doing here is setting the local function variable globalInt to 0.0274

The change doesn't get made, so here, when we echo globalInt, it is going to show 25.0282

When we run the function that is going to try to change the value, it is not going to work.0287

And so, we are still going to see that globalInt outputs 25, as well.0291

I just need to put a break statement here.0296

When we go around to the file, we see that 25 is output twice.0304

And again, the reason for that is that, within a function, you cannot access global variables.0307

At the same time, not only can you not change them, but you cannot access them, either, to output them.0317

For example, let's say we wanted to echo globalInt.0325

Now, one would think, "OK, we have run our script; we set globalInt to 25; we have output it."0330

"We call this function, and the first statement is echo globalInt--well, we would think since globalInt is set to 25, it should output it."0334

It was; but we will see that is not going to be the case; we are actually going to get a notice.0342

It is going to say that you have an undefined variable globalInt.0348

And that is because, within this function, globalInt has yet to be defined.0351

And within a function, it doesn't know about global variables.0354

The other side of that is that, in the global scope, you don't have access to variables defined within a function.0364

For example, we have a function here called localScope; it takes in one parameter, and it creates a variable called localInt=100.0375

Now, this is a local function variable, and what that means is: because it is defined within the function,0383

it is not available here in the outside script.0388

So, even if we were to (let's erase this) attempt to access this variable outside of the function, it wouldn't work,0391

even if we have already called the function.0409

For example, if we go ahead and call the function localScope, and just put a string that says Hello,0411

and now we call this function, it would get run; it would create this variable localInt=100.0427

And then, if we tried to echo that local variable out here, we are going to get an error, because it is defined within the function.0432

It has only function scope; it is not accessible outside the function.0439

So, when we run this, we are going to get another notice, and it is going to say undefined variable localInt on line 35.0443

We look at line 21 that is in our global scope, within the bigger script outside of the function; it doesn't know what localInt refers to.0453

At the same time (for example), we couldn't output param.0462

Even though, within the function, we could echo param that was passed in,0474

and that will work, because variables defined within a function are only available within that function,0479

so it knows about what param is; it is whatever value it was set to when the function was called (in this case, "Hello").0488

It will be able to echo it, but if we go down here and we try to echo it, it is not going to happen, because param only exists within the function.0494

For example, if we run the script, we will see that Hello is output, and then we get an error on line 36.0501

If we look back, Hello gets output because this echo statement knows what param is, because it has been defined within the function scope.0509

However, we get an error here, because we are trying to access the variable param that is only defined within the scope of the function.0518

That is the difference between global scope and local (function) scope.0525

Now, PHP does provide a way of being able to access global variables within functions, and function variables in the global scope.0533

And it does so by the keyword global.0541

What that does is: you can declare a variable within a function, and prepend it with this keyword global,0546

and that is saying that, any time you access that variable within that function,0551

you are going to be referring to the global version of that variable.0555

And you need to do it by declaring it again with the global keyword first.0562

So, for example, if we look at a script called globalKeyword.php, we have a function defined called accessGlobal,0565

which we are going to get to in a second.0575

But what we do is define a global variable called globalInt=25, and then we echo that value.0577

We say, "in global scope, globalInt equals" the value of it, which is going to equal 25.0586

Because we are in the global scope, it knows about that variable.0591

Now, when we call this function, accessGlobal, and we go up here, and in the first line, we try to output globalInt,0595

it doesn't know what globalInt is, because it hasn't been defined within that local function scope yet,0602

and it doesn't have access to global variables.0607

However, if we were to go ahead and redefine the variable by calling the variable name that we want to use0611

(that is a global variable) and prepending it with the keyword global, and then a space,0619

then, when we try to use the variable globalInt within the function, it is going to know that we are referring to the global variable globalInt.0623

So, this echo statement, where we are trying to echo globalInt, will actually work,0631

because the function now knows that globalInt refers to this global access variable.0636

In addition, the other thing we can do is: because now globalInt within the function refers to a global variable,0642

we can change the value of the global variable within the function; we can set it equal to 0.0650

And so, after this function ends, when we try to output globalInt again, it is not going to be 25 anymore; it is going to be 0.0655

So, if we go ahead and run this script, you will see a couple of things.0663

First, we are going to see that the first output of globalInt equals 25; and that comes from this first statement here,0673

where we are in the global scope, and we are able to output this global integer.0680

Now, accessGlobal...the first thing it tries to do is access and output that globalInt, but it doesn't exist,0685

because it's in the global scope, and it doesn't know about global scope variables.0692

So, we get this undefined variable on line 19; it says globalInt is undefined.0696

And when it tries to output it, it outputs a blank, because it has no value for it.0700

If we go back and look at line 19, this is where it is trying to access that global variable.0705

However, now that we have declared it here as a global variable, this echo statement actually works.0710

And so, when we look back at our script, we can see, the second statement in accessGlobal, after the declaration0715

globalInt with the global keyword, it is going to output the value globalInt=25.0723

You also notice that, because globalInt refers to the global variable globalInt now (because of this keyword),0729

we can change the value of it; and so, when we change it to 0 here, and we access it again0738

outside the function after the function has been called, its value is going to be updated.0743

And that is why you see the output here: in the global scope, globalInt is now equal to 0.0748

So now, we are going to talk about superglobals, which again, is a topic we have kind of talked about a little bit before, with the _GET and _SERVER variables.0757

Superglobals are predefined associative arrays by PHP that are always available in any scope.0764

They are available in global scope, and within function scope, which means that because they are global, you can use them0772

in the global scope of the script without a problem, because they are a global variable; but then, in a function, normally,0782

as we just saw, you need to specify with the keyword global in order to use a global variable.0787

Well, superglobals have the advantage of: you don't have to specify the global keyword before using them in a function,0792

like you would any other global variable.0801

Additionally, we are going to introduce a new superglobal called GLOBALS, interestingly enough.0805

And what that superglobal contains: it is an associative array that contains all of the global variables currently defined within your script.0811

And that allows you another way to access global variables within a function, because we know that we can't access global variables0821

within a function without using the global keyword.0829

However, we just learned that superglobals are available everywhere, and because the GLOBALS superglobal array0834

contains all of the global variables available, we can use that to access a global variable in the function.0843

I know it is a lot to soak in--a lot of "global" words being thrown around.0850

Essentially, the way that the GLOBALS array works is that the keys of the array are the identifiers, or the names, of all the current global variables.0854

And the values associated with those keys are just the current values of those global variables.0864

One other thing to mention is that constants, in a way, are kind of like superglobals, in that they are always available in all scopes.0871

They are available within function scopes; they are available within the global scope.0877

And like superglobals, you don't have to declare them within a function using a global keyword.0882

The way that they are not like superglobals is that they are not predefined by PHP.0889

So, let's go and take a look at a script that makes use of superglobals.0894

Here, we have a couple of functions at the top that we are going to talk about in a second.0900

Here we are at the beginning of our script; we are in the global scope--we are not inside a function.0906

And we are going to output the value of the superglobal variable _SERVER ['DOCUMENT_ROOT'].0911

And what that is going to show is that this superglobal is available within the global scope.0917

So, when we go ahead and run the script, the first output we should see is "in the global scope, _SERVER ['DOCUMENT_ROOT']=this."0922

Now, the next thing we do is call a function called useServer; and if we look up at the useServer function, it says,0935

"inside useServer," and it outputs the value of _SERVER ['DOCUMENT_ROOT'].0941

Now, because _SERVER is a superglobal variable, which is available in all scopes, we can access it within the function without using the global keyword.0945

And so, it should output its value; and when we look at the output (let's refresh it) we can see that the second output statement says,0955

"inside useServer, _SERVER ['DOCUMENT_ROOT'] equals" so-and-so.0962

And that shows you that you can access those superglobal variables within a function or in the global scope.0967

The other thing I want to demonstrate is the use of the GLOBALS superglobal that we have just talked about.0977

So, for example, if we define this global variable called globalInt, and we set it equal to 25,0983

and then we call the useGlobal function, if we look up at useGlobal, what it does is: it is trying to output the value of that globalInt variable.0989

Now, normally you have to declare the variable in the function, using the global keyword.1001

However, because all global variables are available within the global superarray, we can actually get access to it.1006

And the way you do that is: you access the GLOBALS superglobal array, and you specify the name GLOBALS,1013

and then use as the key the name of the global variable that you want to output.1026

And this is using the complex curly bracket notation, and what this is saying is,1030

"I want to get the value of the global variable called globalInt."1034

And because GLOBALS is available everywhere, because it is a superglobal, you shouldn't get an error here,1040

and this should work, and it should output the value 25.1045

So, when we go and look at our script, we can see that it says "in the function useGlobal, this variable here, globalInt of the GLOBAL array, equals 25."1048

The other thing is to demonstrate about constants: we define a constant in the global scope called PI.1062

And then, we are going to try to output that constant within the global scope, and we are going to see that that works,1067

because constants have scope everywhere, which means they can be used within functions or within the global scope.1073

So, this is going to work; and then, when we call the function useConstant, and we look up useConstant,1084

it is going to try to output the constant defined in the global scope.1089

Because constants have scope everywhere, it is going to work, and we will have access to it.1093

And so, when we look at our output, we can see: in the global scope, constant PI equals this value;1098

in useConstant function, it has the same value, which shows that you can access that constant1103

within the global scope or within local function scope.1108

We have introduced global variables, and now I just want to talk about some of the pitfalls of using global variables within functions.1115

In general, accessing global variables from within your functions should be avoided.1124

Instead, if you need to use the value of a global variable, you can pass it into the function as a parameter.1131

There are a couple of reasons for that--mainly that, by not accessing global variables within your functions,1137

you can increase the reusability, portability, and maintainability of your code.1145

And the reason for that is: first, by not using global variables, it eliminates a function's dependencies on a particular global variable.1151

For example, let's say you have a function named test, and we access the global variable...1161

maybe there is a global variable that exists that is just called a.1170

So, if we run that function test, and we use it to access a global variable a, as long as a is available as a global variable, that function is going to work.1174

Now, one of the reasons we create functions is to be able to reuse them; so let's say we put that function in a function library,1183

and we move it to our new web application.1189

In our new web application, maybe this variable a is no longer called a; it is called b.1191

Now, that function is not going to work anymore, because it is going to try to access the global variable a that doesn't exist.1198

So, when you include global variables within a function, you are creating dependencies on those global variables existing,1204

reducing the ability to reuse your code and to take it to other applications.1211

The other thing it does is: by not using global variables in functions, it reduces your debugging difficulties related to global variables being unexpectedly edited.1215

For example, if within a function we are using the global variable a, and we are doing some processing on a,1229

we expect a to be whatever the value is when the function started.1241

Now, let's say within our function, we go out and we call another function; let's say we called function test.1245

Maybe the test function is written by someone else, and it goes out and changes the value of a.1251

Now, if we were to go further down our script, and to try and access the a, and let's say we want to echo a,1260

we may have a problem, because we expect a to have the value that it had1272

when we first defined the global variable, when we entered the function.1278

But another function, because it is a global variable, might change that variable; so it can have unintended consequences.1282

And that can cause a problem--that is going to make things harder to debug, because we have to go and look1289

at all the other code, to see if any of the other functions access those global variables.1295

In some cases, which we are going to see more of in the advanced class, using global variables within functions cannot be avoided.1305

And when that happens, you want to make sure that you document these functions extremely well,1313

because that lets any programmers that are going to be using this function know that there is a dependency on a global variable.1319

So, if they want to use that function, they have to make sure that those global variables exist.1324

I just quickly want to mention when variables can be defined.1332

You need to define (and we have kind of seen this implicitly, and haven't really talked about it explicitly) a variable in order to use it.1336

It must be defined before it can be used, and this includes (as we just saw) using global variables within a function.1343

If you want to access a global variable within a function, if you are not using the GLOBALS superglobal array,1350

you need to prepend it with the global keyword; and that is declaring the variable to be available for use in that function.1356

And as we saw when we tried to access a global variable from within a function without using the global keyword,1364

essentially, that variable hadn't been defined yet, and so that is how we saw that we got an error.1370

I just want to show one final example that puts all of this together that we have learned about.1378

We have learned about global variables; we have learned about local variables, which are created for functions.1382

We have formally defined what the superglobals are; we have talked about the scope, as they relate to constants.1388

And then, we are also going to show how scope applies to using variables within include files.1394

So, if we go and look at this script called the beginning of this page, it includes a library called testLIB.php.1400

It has a couple of test functions that we are going to use in the main script.1411

The first thing we do in the beginning of the script is: we define a global integer, and we define a global constant.1417

And then, we are going to show, through three echo statements, that you can access all of these variables within the global scope.1423

One you can directly access, using globalInt; the other one--because it is a global variable,1431

it is maintained in the GLOBALS superglobal array, so you can access it this way, as well.1435

And because constants are available in all scopes, you will be able to output the constant variable.1441

If we go and look at scopeRecap, and load it, we can see at the beginning "global variable and constant access in the global scope."1447

And we can see that, in the global scope, we can access globalInt, and it is equal to 100.1458

We can access it by the GLOBALS array, and then, in the global scope, we also have access to the constant, because constants are declared.1463

Now, the other thing that we have done in this file is shown how scope is affected in include files.1471

And essentially, an include file is just considered a part of the PHP file it is included in.1477

So, any variables that are used in that are globally-scoped variables.1481

If we include this file called testInclude.php, which does the same echo statements we just did (it tries to echo the globalInt variable,1489

just directly accessing it, and tries to access it using the GLOBALS superglobal, and then tries to access it using the constant PI),1497

because it is included in line with that file, it has access to all of those global variables; it is not defined within a function,1505

and so, all of these should be able to output the correct value.1512

So, when we look at our file and output, we can see, in the include file, we have the same output as up here, globalInt=200.1516

We can access it by the GLOBALS array, and it equals the right value; and we can also access the constant PI.1523

The next sort of test we are going to do is trying to access global variables in a function where we don't use the global keyword.1533

We have defined a function in our testLIB called nonGlobalTest.1540

And what that says is: it tries to create a string that directly accesses this globalInt.1544

And we haven't used the global keyword within our function to define that variable, so globalInt, as far as the function is concerned, doesn't exist.1550

So, it is going to generate an error, and then we are just going to echo what the error message is.1557

And if we look at the page, we can see that global variable accessing that function, it generates an error1562

that says it's an undefined variable, globalInt.1568

So now, what we are going to do is define another function, called globalTest.1574

And what we are going to show is that you can access that global variable, as we had learned, if we declare it using the global keyword.1577

And so, once we have made this declaration here that globalInt refers to the global variable globalInt, we can directly use the variable.1585

Additionally, we are going to show that you can access the globalInt variable using the GLOBALS superarray,1594

and we are also going to show that, within a function, you can access constants, because constants have global scope.1602

In scopeRecap, if we look down and run globalTest, we can see that, in the function globalTest,1608

globalInt=100 when we prepend it with the global keyword, which means it is giving us access to the global variable.1618

We can access the variable using the GLOBALS superarray, and we can also see that the constant is available within the function.1627

We have also defined a function called localTest, which has a parameter that gets passed in, and it defines a local variable.1635

And in the function, it outputs the value of the parameter passed in, and it outputs the value of the local variable.1642

And this is going to show that, because localVar is defined within this function, and param is defined as part of the function's parameter list,1648

they are going to be available within that function, so these outputs should work.1656

So, in scopeRecap, when we call localTest with this string param value, we can see that, in localTest, localVar=local,1659

which is the value we had set it to within the function.1673

And we can see that param has the value 'param value,' which is passed in.1676

Now, just to show the other side of it, in the global scope, now, we are going to try to output1681

the variables that were defined in the function: the localVar variable,1690

and then also the param variable, which is defined as part of the function.1695

And you can see here, we have error suppression operators, because you are going to generate a warning, because those variables aren't available.1699

It is just going to output them, and it is going to say these variables don't exist within the scope.1705

And as you can see, it says "undefined variable localVar," "undefined variable param."1710

So, this is sort of an example that you can look at and see all of the different interactions--1714

how scope interacts in all sorts of different ways when using functions, when using constants, when using superglobals,1719

being able to access function variables outside of functions, being able to access variables within include files, and so forth.1726

It kind of sums everything up.1733

So, I'll just quickly mention this: it doesn't fall under the function of variable scope, but because we are talking about scope,1737

I want to mention that functions have a scope as well.1742

A function has a name, which is an identifier; and as we know with variables,1747

variable scope defines where that identifier has meaning--where you can use that identifier.1751

Well, functions in general have global scope, just like constants and superglobals; they are available everywhere.1756

So, you can call a function within the global part of your script, or you can call it within another function.1760

It also can be called within any include files that you include within your main file.1766

And the main thing about it is: because they have global scope, they never need to be defined with the keyword global.1776

For today's homework challenge, I want you to get a little practice with trying to understand this scope concept that we have introduced.1783

I would like you to create a script that defines a variable and a constant.1790

And when you define them in the main script, that means that those variables have global scope.1794

And then, I want you to go ahead and output them, to show that within the script, you have access to those variables.1800

Then, define a function that takes one parameter and also defines one local variable within its function body.1806

And then, what I want you to do is, within the function, also try to output the global variable that you defined in step 1,1815

without using the global keyword, and without using the GLOBALS array.1824

And what you should see is: you should get an error that you are not able to access that.1828

Then, go ahead and use both the global keyword and the GLOBALS superglobal to access that global variable from within the function,1833

to give you practice with using the global keyword and the superglobals array.1842

Also, try outputting the constant that you defined in your main script from within the function,1849

to show that constants have global scope, and they are available within the function, as well.1855

Then, because the function has a parameter and a locally defined variable,1861

I want you to output both the parameter and that locally defined variable from within the function.1864

That is going to show you that these function variables, including the parameter, have scope within the function.1870

And then, try outputting the function parameter and the variable that you created locally within the function outside the function,1875

after the function has been called within global scope.1882

And you will see that you should get an error, because those variables have local function scope and are not available in the global scope.1884

That ends today's lesson; thank you for watching look forward to seeing you next time.1892