Function & global scope in PHP

Let’s grab our $posts array and move it so that it’s within these curly brackets.

function getPosts()
{
    $posts = [
        [
            'title' => 'How to learn PHP',
            'content' => 'This is how you learn PHP.',
        ],
        [
            'title' => 'How to learn MySQL',
            'content' => 'This is how you learn MySQL.',
        ],
        [
            'title' => 'How to learn Nginx',
            'content' => 'This is how you learn Nginx.',
        ],
    ];
}

Note how immediately our $posts variable reference that is outside of the function is invalid. If we hover over this code hint, it tells us that $posts is an undefined variable. This is due to something called scope.

There are different scopes in PHP. The function completely encapsulates the code within it.

If we move the $title variable above the function, then try to reference $title within the function, notice how we will get the same “undefined variable” notice within the function.

<?php
$title = 'My Blog';
function getPosts()
{
    $title;
    $posts = [
        [
...

So, we now know that functions cannot access variables outside of the function, and code outside of the function cannot access variables in the function. This is what “scope” is — it’s a barrier so that code can’t get in or leak out of encapsulated code.

You might think this is absolutely horrible! But 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.

Note that we do have access to the global scope within our function, which means we can call all of PHP’s built-in functions within our functions. However, code within our functions cannot be directly called from outside of the function.

Complete and Continue  
Extra lesson content locked
Enroll to access source code, comments & track progress.
Enroll for Free to Unlock