Scope in PHP is how variables are encapsulated in pieces of code. Let's learn about function & global scope in PHP.
Instructor: [0:00] Now that we have our function created, let's grab this entire post array and go ahead and move it into the getPost function. If we scroll down, we'll see immediately that our POST variable is returning undefined. This is due to something called scope.
[0:20] There are different scopes in PHP, and the function completely encapsulates the code within the brackets. This means that the POST variable within the getPost function is inaccessible to code outside of the function. Similarly, if we grab this title variable and place it above the function and then try to reference it within this function, we will see that it is also returned as undefined.
[0:53] We now know that functions cannot access variables outside of a function and code outside of a function cannot access variables in a function. This is what scope is. It's a barrier so that code can't get in or leak out of encapsulated code.
[1:10] You might think this is absolutely horrible, but actually the opposite is true. Since nothing can get in or out, our encapsulated code provides us with deterministic reliability. This means that when we call our function, we know we will get a consistent result even if external variables change. If we didn't have the concept of scope, we would be unable to write programs that were reliable.
[1:35] Note that we do have access to the global scope within our function, which means that we can call any of the built-in PHP functions within our functions. However, code within our functions cannot be directly called from outside of the function.
Member comments are a way for members to communicate, interact, and ask questions about a lesson.
The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io
Be on-Topic
Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.
Avoid meta-discussion
Code Problems?
Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context
Details and Context
Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!