Skip to Content
PHP 5 Kochbuch, Third Edition
book

PHP 5 Kochbuch, Third Edition

by David Sklar, Adam Trachtenberg, Carsten Lucke, Matthias Brusdeylins, Ulrich Speidel, Stephan Schmidt
September 2009
Intermediate to advanced content levelIntermediate to advanced
912 pages
48h 11m
German
O'Reilly Verlag
Content preview from PHP 5 Kochbuch, Third Edition

5.5 Statische Variablen verwenden

Problem

Sie benötigen eine lokale Variable, die ihren Inhalt zwischen zwei Aufrufen einer Funktion behält.

Lösung

Deklarieren Sie die Variable als statisch (static):

function track_times_called() {
    static $i = 0;
    $i++;
    return $i;
}

Diskussion

Wenn eine Variable als static deklariert ist, erinnert sich eine Funktion an sie. Wenn es also nachfolgende Aufrufe der Funktion gibt, können Sie auf den Wert der gespeicherten Variablen zugreifen. Die in Listing 5.1 dargestellte Funktion pc_check_the_count() verwendet statische Variablen, um die Strikes und Bälle in einem Baseball-Spiel zu verfolgen.

function pc_check_the_count($pitch) { static $strikes = 0; static $balls = 0; switch ($pitch) { case 'foul': if (2 == $strikes) break; ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP programmieren unter Windows

PHP programmieren unter Windows

Arno Hollosi

Publisher Resources

ISBN: 9783868993271Purchase book