Zoeken…


Invoering

Variabel bereik verwijst naar de codegebieden waar toegang tot een variabele kan worden verkregen. Dit wordt ook wel zichtbaarheid genoemd . In PHP scope worden blokken gedefinieerd door functies, klassen en een globale scope die beschikbaar is in een applicatie.

Door de gebruiker gedefinieerde globale variabelen

Het bereik buiten een functie of klasse is het globale bereik. Wanneer een PHP-script een ander bevat ( include of require ), blijft het bereik hetzelfde. Als een script buiten een functie of klasse is opgenomen, zijn de globale variabelen in hetzelfde globale bereik opgenomen, maar als een script vanuit een functie is opgenomen, vallen de variabelen in het opgenomen script binnen het bereik van de functie.

Binnen het bereik van een functie of klassemethode kan het global trefwoord worden gebruikt om een door de gebruiker gedefinieerde globale variabelen te creëren.

<?php

$amount_of_log_calls = 0;

function log_message($message) {
    // Accessing global variable from function scope
    // requires this explicit statement
    global $amount_of_log_calls;

    // This change to the global variable is permanent
    $amount_of_log_calls += 1;

    echo $message;
}

// When in the global scope, regular global variables can be used
// without explicitly stating 'global $variable;'
echo $amount_of_log_calls; // 0

log_message("First log message!");
echo $amount_of_log_calls; // 1

log_message("Second log message!");
echo $amount_of_log_calls; // 2

Een tweede manier om toegang te krijgen tot variabelen vanuit de globale scope is om de speciale PHP-gedefinieerde $ GLOBALS-array te gebruiken.

De $ GLOBALS-array is een associatieve array met de naam van de globale variabele als sleutel en de inhoud van die variabele is de waarde van het array-element. Merk op hoe $ GLOBALS in elk bereik bestaat, dit komt omdat $ GLOBALS een superglobal is.

Dit betekent dat de functie log_message() kan worden herschreven als:

function log_message($message) {
    // Access the global $amount_of_log_calls variable via the
    // $GLOBALS array. No need for 'global $GLOBALS;', since it
    // is a superglobal variable.
    $GLOBALS['amount_of_log_calls'] += 1;

    echo $messsage;
}

Men zou zich kunnen afvragen, waarom de $ GLOBALS-array gebruiken wanneer het global trefwoord ook kan worden gebruikt om de waarde van een globale variabele te krijgen? De belangrijkste reden is dat het gebruik van het global sleutelwoord de variabele binnen bereik zal brengen. U kunt dan niet dezelfde variabelenaam opnieuw gebruiken in het lokale bereik.

Superglobal-variabelen

Superglobal-variabelen worden gedefinieerd door PHP en kunnen altijd overal worden gebruikt zonder het global trefwoord.

<?php

function getPostValue($key, $default = NULL) {
    // $_POST is a superglobal and can be used without
    // having to specify 'global $_POST;'
    if (isset($_POST[$key])) {
        return $_POST[$key];
    }

    return $default;
}

// retrieves $_POST['username']
echo getPostValue('username');

// retrieves $_POST['email'] and defaults to empty string
echo getPostValue('email', '');

Statische eigenschappen en variabelen

Statische klasse-eigenschappen die zijn gedefinieerd met de public zichtbaarheid zijn functioneel hetzelfde als globale variabelen. Ze zijn overal toegankelijk waar de klasse is gedefinieerd.

class SomeClass {
    public static int $counter = 0;
}

// The static $counter variable can be read/written from anywhere
// and doesn't require an instantiation of the class
SomeClass::$counter += 1;

Functies kunnen ook statische variabelen definiëren binnen hun eigen bereik. Deze statische variabelen blijven bestaan via meerdere functie-aanroepen, in tegenstelling tot reguliere variabelen die in een functiebereik zijn gedefinieerd. Dit kan een zeer eenvoudige en eenvoudige manier zijn om het ontwerppatroon van Singleton te implementeren:

class Singleton {
    public static function getInstance() {
        // Static variable $instance is not deleted when the function ends
        static $instance;

        // Second call to this function will not get into the if-statement,
        // Because an instance of Singleton is now stored in the $instance
        // variable and is persisted through multiple calls
        if (!$instance) {
            // First call to this function will reach this line,
            // because the $instance has only been declared, not initialized
            $instance = new Singleton();
        }

        return $instance;

    }
}

$instance1 = Singleton::getInstance();
$instance2 = Singleton::getInstance();

// Comparing objects with the '===' operator checks whether they are
// the same instance. Will print 'true', because the static $instance
// variable in the getInstance() method is persisted through multiple calls
var_dump($instance1 === $instance2);


Modified text is an extract of the original Stack Overflow Documentation
Licentie onder CC BY-SA 3.0
Niet aangesloten bij Stack Overflow