Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Scope

The scope, also called context, is the space in which a certain elements are defined. There are function, closure or method scope, for local variables; methods are also defined in a class scope.

A variable scope is usually its host method, or the file in which is used. It also extends to any included files, and skips other method definition.

Arrow functions are initialised with the same scope than the defining scope, but do not write back in it. Closure with the use keyword also import variables from the defining scope.

Scopes are generally considered as global or local.

<?php

    // $trunk is defined in the file scope
    $trunk = 1;

    // $trunk is extended to the included scope
    include 'b.php';

    // arrow functions use the same scope than the defining code.
    // here, $trunk is also defined there.
    // $herd will not be available in the calling scope.
    $herd = fn () => $trunk + ($herd = 2);

    function trumpet() {
        // $tusk is only defined in the trumpet() function
        echo $tusk;
    }

?>

Documentation

See Also