What’s the deal with scope?
Lab: PHP 101: Gentle Introduction to WordPress Programming
Video Runtime: 08:34
What is the deal with scope? If you are working on a theme or some code, you’ll hear about scope. Or maybe you’ve tried to access a variable that’s in another function and you don’t understand why you can’t access it. Why? How about the global variables? Let’s talk about scope.
Scope defines what parts of your code can access other code. In this episode, we’ll talk specifically about variables and their scope.
Variables have scope. They belong to some access level. Variables within a function belong to that function. The function can use them, but code outside of that function cannot. You can’t access them from the global space or another function. Why? They belong only to the function that controls its code block.
More technical information: Once the function runs, the variable exists in memory. But as soon as the function is done running, the variable(s) within that function no longer exist.
Let’s do an exercise to show you how scope works. Here’s the code you’ll use:
<?php | |
$global_variable = 'I am a global variable'; | |
d( $global_variable ); | |
function test_scope( $local_variable ) { | |
$local_variable .= ' I am only accessible to my function!'; | |
echo '========= in the test_scope function ========'; | |
d( $local_variable ); | |
d( $global_variable ); | |
} | |
//test_scope( 'testing from global space' ); | |
d( $local_variable ); | |
ddd( $global_variable ); |
Want to know more about scope? Check out the PHP Variables Bootcamp for a deeper dive into scope.
Challenge Yourself
-
Can a function access another function's variable?
-
How can a function use a global variable?
$post_id = 10; function load_the_defaults() { d( $post_id ); } load_the_defaults();
-
For the above code, what is the value of the variable $post_id within the function?
Once upon a time, there was a developer... You! This is going to be a good story...
Episodes
Total Lab Runtime: 03:21:32
- 1 Lab Introductionfree 11:37
- 2 What is PHP? Why use it?free 17:49
- 3 Why and how does WordPress use PHP?free 07:33
- 4 Syntax Basicsfree 18:34
- 5 What's the deal with Variables?free 27:05
- 6 Break Up Code into Logical Partsfree 07:55
- 7 Subroutines - Behold the functionfree 14:11
- 8 Loading Files to Runfree 13:20
- 9 To Run or Not to Run - Making Decisionsfree 19:07
- 10 Sequencing - Yup, code runs in orderfree 06:16
- 11 Repeating code using Loopsfree 13:57
- 12 Building Strings with Dots and Variablesfree 15:10
- 13 What's the deal with scope?free 08:34
- 14 Naming Stufffree 06:18
- 15 Putting it All Togetherfree 08:33
- 16 Where do I go from here?free 05:33