PHP-Handbuch

von:
Mehdi Achour
Friedhelm Betz
Antony Dovgal
Nuno Lopes
Hannes Magnusson
Georg Richter
Damien Seguy
Jakub Vrana
2009-10-30
Herausgegeben von: Philip Olson
Bei der Übersetzung wirkten mit:
Florian Anderiasch
Arne Blankerts
Cornelia Boenigk
Timo Buhmann
Hartmut Holzgraefe
Daniel Jänecke
Hakan Kücükyilmaz
Carola Kummert
Sebastian Nohn
Dirk Randhahn
Thorsten Rinne
Martin Samesch
Mark Wiesemann

Copyright

Copyright © 1997 - 2009 by the PHP Documentation Group. Dieses Material darf nur gemäß den Regeln und Bedingungen der Creative Commons Attribution License Version v3.0 oder neuer weiter verbreitet werden. Eine Kopie der Creative Commons Attribution 3.0 license ist in diesem Handbuch enthalten, die aktuellste Version ist unter » http://creativecommons.org/licenses/by/3.0/ verfügbar.

Für den Fall, dass Sie daran interessiert sind, dieses Dokument weiter zu verbreiten oder in sonstiger Form zu veröffentlichen, in Teilen oder als Ganzes, entweder verändert oder unverändert, und Sie Fragen haben, können Sie Kontakt zu den Copyright-Inhabern über » doc-license@lists.php.net. aufnehmen. Bitte beachten Sie, dass das Archiv dieser Maillingliste öffentlich zugänglich ist.



PHP-Handbuch


Vorwort

PHP ist die Abkürzung für "PHP: Hypertext Preprocessor", eine weitverbreitete Open Source Skriptsprache speziell für Webentwicklungen. PHP läßt sich in HTML einbinden. Die Syntax erinnert an C, Java und Perl und ist einfach zu erlernen. Das Hauptziel dieser Sprache ist es, Webentwicklern die Möglichkeit zu geben, schnell dynamisch generierte Webseiten zu erzeugen. Aber Sie können PHP für weitaus mehr einsetzen.

Dieses Handbuch besteht vorranging aus einer Funktionsreferenz, enthält aber zusätzlich auch eine Sprachreferenz, Erläuterungen zu den wichtigsten Features und weitere ergänzende Informationen.

Sie können dieses Handbuch in verschiedenen Formaten unter » http://www.php.net/download-docs.php herunterladen. Informationen dazu, wie dieses Handbuch erstellt wird, finden Sie im Anhang unter dem Kapitel 'Über dieses Handbuch'. Wenn Sie sich für die Geschichte von PHP interessieren, lesen Sie bitte den entsprechenden Anhang.

Autoren und Mitwirkende

Wir heben die zur Zeit aktivsten Personen auf der Titelseite des Handbuchs hervor, aber es gibt viel mehr Mitwirkende, die zur Zeit mithelfen oder in der Vergangenheit einen großen Beitrag zu diesem Projekt geleistet haben. Ebenfalls gibt es eine Vielzahl von Personen, die hier nicht namentlich aufgeführt sind, die durch ihre User Notes auf den Handbuchseiten mithelfen. Die User Notes werden kontinuierlich in unser Handbuch integriert und wir schätzen diese Unterstützung außerordentlich. Alle folgenden Listen sind alphabetisch sortiert.

Autoren und Editoren

Folgende Personen verdienenen Anerkennung dafür, dass Sie wesentlichen Inhalt zum Handbuch beigetragen haben und/oder weiterhin beitragen werden: Bill Abt, Jouni Ahto, Alexander Aulbach, Daniel Beckham, Stig Bakken, Jesus M. Castagnetto, Ron Chmara, Sean Coates, John Coggeshall, Simone Cortesi, Markus Fischer, Wez Furlong, Sara Golemon, Rui Hirokawa, Brad House, Pierre-Alain Joye, Etienne Kneuss, Moriyoshi Koizumi, Rasmus Lerdorf, Andrew Lindeman, Stanislav Malyshev, Rafael Martinez, Rick McGuire, Yasuo Ohgaki, Derick Rethans, Rob Richards, Sander Roobol, Egon Schmid, Thomas Schoefbeck, Sascha Schumann, Dan Scott, Masahiro Takagi, Michael Wallner, Lars Torben Wilson, Jim Winstead, Jeroen van Wolffelaar und Andrei Zmievski.

Folgende Personen haben durch Ihre Editionsarbeit wesentlich zum Handbuch beigetragen: Stig Bakken, Gabor Hojtsy, Hartmut Holzgraefe und Egon Schmid.

User Note-Betreuer

Die zurzeit aktivsten Betreuer: Daniel Brown, Nuno Lopes, Felipe Pena, Thiago Pojda und Maciek Sokolewicz.

Auch folgende Personen haben einiges an Mühe und Zeit zur Betreuung der User Notes investiert: Mehdi Achour, Daniel Beckham, Friedhelm Betz, Victor Boivie, Jesus M. Castagnetto, Nicolas Chaillan, Ron Chmara, Sean Coates, James Cox, Vincent Gevers, Sara Golemon, Zak Greant, Szabolcs Heilig, Oliver Hinckel, Hartmut Holzgraefe, Etienne Kneuss, Rasmus Lerdorf, Matthew Li, Andrew Lindeman, Aidan Lister, Hannes Magnusson, Maxim Maletsky, Bobby Matthis, James Moore, Philip Olson, Sebastian Picklum, Derick Rethans, Sander Roobol, Damien Seguy, Jason Sheets, Tom Sommer, Jani Taskinen, Yasuo Ohgaki, Jakub Vrana, Lars Torben Wilson, Jim Winstead, Jared Wyles und Jeroen van Wolffelaar.




Einführung


Introduction

Inhaltsverzeichnis


Was ist PHP?

PHP (rekursives Akronym fürPHP: Hypertext Preprocessor) ist eine weit verbreitete und für den allgemeinen Gebrauch bestimmte Open Source-Skriptsprache, welche speziell für die Webprogrammierung geeignet ist und in HTML eingebettet werden kann.

Nett, aber was heißt das genau? Ein Beispiel:

Beispiel #1 Ein einführendes Beispiel

<!DOCTYPE HTML PUBLIC "-//W3C/DTD HTML 4.01 Transitional//EN
"http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <title>Beispiel</title>
    </head>
    <body>

        <?php
        
echo "Hallo, ich bin ein PHP-Skript!";
        
?>

    </body>
</html>

Anstatt ein Programm mit vielen Anweisungen zur Ausgabe von HTML zu schreiben, schreibt man etwas HTML und bettet einige Anweisungen ein, die irgendetwas tun (wie hier "Hallo, ich bin ein PHP-Skript!" auszugeben). Der PHP-Code steht zwischen speziellen Anfangs- und Abschluss-Verarbeitungsinstruktionen <?php und ?>, mit denen man in den "PHP-Modus" und zurück wechseln kann.

PHP unterscheidet sich von clientseitigen Sprachen wie Javascript dadurch, dass der Code auf dem Server ausgeführt wird und dort HTML-Ausgaben generiert, die an den Client gesendet werden. Der Client erhält also nur das Ergebnis der Skriptausführung, ohne dass es möglich ist herauszufinden, wie der eigentliche Code aussieht. Sie können Ihren Webserver auch anweisen, alle Ihre HTML-Dateien mit PHP zu parsen, denn dann gibt es wirklich nichts, das dem Benutzer sagt, was Sie in petto haben.

Das Beste an der Verwendung von PHP ist, dass es für Neueinsteiger extrem einfach ist, aber auch einen riesigen Funktionsumfang für den professionellen Programmierer bietet. Scheuen Sie sich nicht, die lange Liste der PHP-Funktionen zu lesen. Sie können einsteigen, und binnen weniger Stunden bereits mit dem Schreiben von einfachen Skripten beginnen.

Auch wenn die Entwicklung von PHP auf serverseitige Programmierung fokussiert ist, können Sie mit PHP weitaus mehr anstellen. Lesen Sie mehr im Abschnitt Was kann PHP? oder oder benutzen Sie direkt das Einführungstutorial, wenn Sie nur an Webprogrammierung interessiert sind.



Was kann PHP?

Alles. PHP ist hauptsächlich auf serverseitige Skripte fokussiert, weshalb Sie alles tun können, was auch ein anderes CGI-Programm kann, wie z.B. Formulardaten sammeln, dynamische Inhalte für Webseiten generieren oder Cookies senden und empfangen. Aber PHP kann noch viel mehr.

Es gibt drei Hauptgebiete, in denen PHP-Skripte genutzt werden.

  • Serverseitige Programmierung. Dies ist das traditionelle und auch Hauptfeld von PHP. Sie benötigen drei Dinge, um damit arbeiten zu können: Den PHP-Parser (CGI oder Server-Modul), einen Webserver und einen Webbrowser. Sie müssen einen Webserver laufen lassen, der mit einer PHP-Installation verbunden ist. Sie können auf die Ausgabe Ihres PHP-Programms mittels eines Webbrowsers zugreifen, der die Seite mithilfe des Servers darstellt. Dieses gesamte Szenario können Sie auf Ihrem heimischen Rechner laufen lassen, wenn Sie erst einmal mit PHP-Programmierung experimentieren wollen. Weitere Informationen finden Sie im Abschnitt Installation.
  • Kommandozeilenprogrammierung. Es ist auch möglich PHP-Skripte schreiben, die ohne einen Server oder Browser arbeiten können. Sie benötigen dafür nur den PHP-Parser. Die Art der Nutzung ist ideal für Programme, die regelmäßig mitels cron (auf *nix oder Linux) oder dem Task Scheduler (unter Windows) ausgeführt werden. Die Skripte können außerdem verwendet werden, um einfache Textprozessierung auszuführen. Weitere Informationen dazu finden Sie im Abschnitt Verwendung von PHP auf der Eingabezeile.
  • Schreiben von Desktop-Applikationen. PHP ist wahrscheinlich nicht die allerbeste Sprache, um Desktop-Anwendungen mit grafischer Oberfläche zu schreiben, aber wenn Sie PHP sehr gut kennen und einige weiterführende PHP-Features in Ihren clientseitigen Applikationen nutzen möchten, können Sie PHP-GTK nutzen, um derartige Programme zu schreiben. Auf diese Art haben Sie auch die Möglichkeit, plattformübergreifende Applikationen zu schreiben. PHP-GTK ist eine Erweiterung von PHP, die in der Hauptdistribution nicht enthalten ist. Sollten Sie daran interessiert sein, besuchen Sie die » PHP-GTK Website.

PHP kann auf allen gängigen Betriebssystemen verwendet werden, inkl. Linux, vielen Unix-Varianten (inkl. HP-UX, Solaris und OpenBSD), Microsoft Windows, Mac OS X, RISC OS, und wahrscheinlich anderen. PHP unterstützt auch die meisten der heute gebräuchlichen Webserver. Dies umfasst Apache, Microsoft Internet Information Server, Personal Web Server, Netscape- und iPlanet-Server, Oreilly Website Pro-Server, Caudium, Xitami, OmniHTTPd und viele andere. Für den Großteil der Server bietet PHP ein eigenes Modul, für die anderen, die den CGI-Standard unterstützen, kann PHP als CGI-Prozessor arbeiten.

So haben Sie die Freiheit, PHP auf dem Betriebssystem und dem Webserver Ihrer Wahl laufen zu lassen. Weiterhin können Sie je nach Vorliebe prozedural oder objektorientiert programmieren oder eine Mischung aus beidem verwenden. Auch wenn in PHP 4 noch nicht jedes Standard-OOP-Feature implementiert ist, sind viele Codebibliotheken und große Applikationen (unter anderem die PEAR-Bibliothek) bereits ausschließlich objektorientiert programmiert. Mit PHP 5 werden die objektorientierten Schwächen von PHP 4 behoben und ein vollständiges Objektmodell eingeführt.

Mit PHP sind Sie nicht auf die Ausgabe von HTML beschränkt. Seine Fähigkeiten umfassen auch das dynamische Generieren von Bildern, PDF-Dateien und Flashanimationen (mittels libswf und Ming). Sie können auch leicht jede Art von Text, wie XHTML oder irgendeine andere XML Datei, ausgeben. PHP kann diese Dateien automatisch generieren und im Dateisystem speichern anstatt diese nur auszugeben. Auf diese Weise lässt sich ein serverseitiger Cache Ihrer dynamischen Inhalte erstellen.

Vielleicht die größte und bemerkenswerteste Stärke von PHP ist seine Unterstützung für eine breite Masse von Datenbanken. Eine datenbankgestützte Website zu erstellen ist unglaublich einfach. Die folgenden Datenbanken werden zur Zeit unterstützt:

  • Adabas D
  • dBase
  • Empress
  • FilePro (nur Lesezugriff)
  • Hyperwave
  • IBM DB2
  • Informix
  • Ingres
  • InterBase
  • FrontBase
  • mSQL
  • Direct MS-SQL
  • MySQL
  • ODBC
  • Oracle (OCI7 und OCI8)
  • Ovrimos
  • PostgreSQL
  • Solid
  • SQLite
  • Sybase
  • Velocis
  • Unix dbm

Wir haben auch eine Extension zur Datenbankabstraktion (names PDO), welche Ihnen die transparente Verwendung irgendeiner von dieser Erweiterung unterstützten Datenbank erlaubt. Desweiteren unterstützt PHP ODBC, den Open Database Connection Standard, mit welchem Sie sich mit jeder anderen Datenbank verbinden können, die diesen weltweiten Standard unterstützt.

PHP unterstützt auch die Kommunikation mit anderen Services, welche Protokolle wie LDAP, IMAP, SNMP, NNTP, POP3, HTTP, COM (auf Windows) und unzählige andere unterstützen. Sie können auch einfache Netzwerk-Sockets öffnen und unter Verwendung irgendeines anderen Protokolls kommunizieren. PHP unterstützt auch WDDX (Web Distributed Data Exchange) zum Austausch komplexer Daten zwischen Programmiersprachen. Da wir gerade vom Zusammenwirken sprechen: PHP unterstützt auch die Instantiierung von Java-Objekten und deren transparente Verwendung als PHP-Objekte. Sie können auch unsere CORBA-Erweiterung verwenden, um auf entfernte Objekte zuzugreifen.

PHP verfügt über äußerst hilfreiche Textverarbeitungsfunktionen, von den regulären Ausdrücken (POSIX erweitert oder Perl) bis zum Parsen von XML-Dokumenten. Für den Zugriff und das Parsen von XML-Dokumenten unterstützt PHP 4 die Standards SAX und DOM. Sie können außerdem die XSLT-Extension verwenden, um XML-Dokumente zu transformieren. PHP 5 vereinheitlicht all diese XML-Extensions auf der soliden Basis der libxml2-Bibliothek und erweitert diese Funktionalität durch die hinzugefügte Unterstützung von SimpleXML and XMLReader.

Es gibt noch viele andere interessante Erweiterungen, wie mnoGoSearch für Suchmaschinen, die IRC-Gateway-Funktionen, viele Komprimierungswerkzeuge (gzip, bz2, zip), Kalenderumrechnung, Übersetzung uws.

Wie Sie sehen können, reicht diese Seite nicht aus, um alle Möglichkeiten und Vorteile von PHP aufzulisten. Lesen Sie im Abschnitt Installation weiter und konsultieren Sie auch die Funktionsreferenz für weitere Erläuterungen der einzelnen hier erwähnten Erweiterungen.




Auf diesen Seiten möchten wir Ihnen die Grundlagen von PHP in einem kleinen Tutorial vorstellen. Dieser Text behandelt nur das Erstellen von dynamischen Web-Seiten, obwohl PHP natürlich nicht nur dafür geeignet ist. Weitere Informationen finden Sie im Abschnitt Was kann PHP?.

Mit PHP erweiterte Web-Seiten werden wie normale HTML-Seiten behandelt. Sie können sie genauso wie normale HTML-Seiten erstellen und bearbeiten.


Was brauche ich?

In diesem Tutorial gehen wir davon aus, dass auf Ihrem Server die PHP-Unterstützung aktiviert ist und dass die Dateiendung .php PHP zugeordnet ist. Auf den meisten Servern ist dies die Standardeinstellung für PHP-Dateien, aber fragen Sie bitte Ihren Server-Administrator, um sicherzugehen. Wenn Ihr Server PHP unterstützt, müssen Sie nichts machen. Erstellen Sie einfach Ihre .php-Dateien und legen Sie diese in Ihr Web-Verzeichnis - der Server wird sie dann für Sie parsen. Sie müssen nichts kompilieren und auch keine Zusatz-Tools installieren. Stellen Sie sich diese PHP-erweiterten Dateien wie normale HTML-Seiten mit einer ganzen Familie von "magischen" Tags, die Sie verschiedenste Dinge tun lassen, vor. Die meisten Webhoster unterstützen PHP auf ihren Servern. Wenn Ihr Hoster dies nicht tut, dann können Sie auf der Seiter » PHP Links solche Hoster finden.

Angenommen, Sie möchten Bandbreite sparen und lokal entwickeln. In diesem Fall müssen Sie einen Webserver wie z.B. » Apache und natürlich » PHP installieren. Sehr empfehlenswert ist auch die Installation einer Datenbank wie z.B. » MySQL.

Sie können diese Programme entweder eins nach dem anderen selbst installieren oder den folgenden einfacheren Weg gehen. Unser Handbuch bietet ausführliche Installationsanweisungen für PHP (dabei gehen wir davon aus, dass Sie schon einen Webserver installiert haben). Falls Sie Probleme bei der Installation von PHP haben, dann empfehlen wir Ihnen, dass Sie Ihre Fragen auf unserer » Installations-Mailingliste stellen. Noch einfacher ist es, » vorkonfigurierte Pakete für Ihr Betriebssystem zu benutzen, die alle oben genannten Programm mit einigen wenigen Mausklicks installieren. Es ist ziemlich einfach, einen Webserver mit PHP-Unterstützung auf jedem Betriebssystem, wie MacOSX, Linux5oder Windows, aufzusetzen. Unter Linux sind » rpmfind und » PBone hilfreich, wenn Sie RPM-Pakete suchen. Wenn Sie Pakete für Debian suchen, dann besuchen Sie bitte » apt-get.



Ihre erste PHP-erweiterte Seite

Erstellen Sie eine Datei mit dem Namen hallo.php und speichern Sie sie im Root-Verzeichnis Ihres Webservers (DOCUMENT_ROOT) mit dem folgenden Inhalt:

Beispiel #1 Unser erstes PHP-Skript: hallo.php

<html>
 <head>
  <title>PHP-Test</title>
 </head>
 <body>
 <?php echo '<p>Hallo Welt</p>'?>
 </body>
</html>

Benutzen Sie Ihren Browser, um die Datei über den Webserver-URL aufzurufen. Der URL muss mit /hallo.php enden. Wenn Sie lokal entwickeln, sieht der URL z.B. so aus: http://localhost/hallo.php oder http://127.0.0.1/hallo.php - andere Adressen sind aber, abhängig vom Webserver, auch möglich. Wenn Sie alles korrekt installiert haben, wird die Datei von PHP geparst und Sie werden die folgende Ausgabe in Ihrem Browser sehen:

<html>
 <head>
  <title>PHP-Test</title>
 </head>
 <body>
 <p>Hallo Welt</p>
 </body>
</html>

Das Beispiel ist extrem einfach und natürlich brauchen Sie PHP nicht, um eine Seite wie diese zu erstellen. Denn es macht nicht mehr, als Hallo Welt mit der echo()-Anweisung von PHP auszugeben. Bitte beachten Sie, dass die Datei nicht ausführbar sein muss. Der Server erkennt anhand der Dateiendung ".php", dass sie durch PHP interpretiert werden muss. Stellen Sie sich eine normale HTML-Datei vor, die eine Menge von speziellen Tags enthält, mit denen Sie einige interessante Dinge tun können.

Wenn Sie dieses Beispiel ausprobiert haben und Sie aber keine Ausgabe erhalten haben oder zum Download aufgefordert worden sind oder die komplette Datei als Text erhalten haben, dann ist es sehr wahrscheinlich, dass auf Ihrem Server PHP nicht aktiviert oder falsch konfiguriert ist. Fragen Sie in diesem Fall Ihren Administrator und weisen Sie ihn auf das Installations-Kapitel hin. Wenn Sie lokal entwickeln, lesen Sie bitte das Installations-Kapitel, um festzustellen, ob alles richtig konfiguriert wurde. Stellen Sie sicher, dass Sie die datei über das HTTP-Protokoll aufrufen können. Wenn Sie die Datei direkt aus Ihrem Dateisystem aufrufen, wird sie nicht durch PHP geparst. Sollten Ihre Probleme nach Lesen dieses Kapitels immer noch bestehen, zögern Sie nicht und nutzen Sie eines der vielen » Support-Angebote.

Der wichtigste Punkt im Beispiel ist, Ihnen das spezielle PHP Tag-Format zu zeigen. Im Beispiel wurde <?php verwendet, um den Beginn eines PHP-Tags zu kennzeichnen. Anschließend folgte die PHP-Anweisung. Mit dem schließenden Tag, ?>, wurde der PHP-Modus wieder verlassen. Sie können an jeder Stelle und so oft Sie wollen, in den PHP-Modus wechseln und ihn wieder verlassen. Für weitere Details lesen Sie bitte den Abschnitt zu den Grundlagen der Syntax von PHP.

Hinweis: Anmerkungen zu Zeilenwechseln
Zeilenwechsel sind in HTML nur von geringer Bedeutung, trotzdem ist es sinnvoll HTML Code durch Zeilenwechsel zu formatieren um die Lesbarkeit zu erhöhen. Ein Zeilenwechsel der direkt auf ein schließendes ?>> folgt wird von PHP bei der Ausgabe entfernt. Dies ist äußerst nützlich wenn Sie viele PHP-Blöcke einfügen oder Dateien includieren die keine Ausgabe erzeugen sollen, auf der anderen Seite kann es aber auch verwirrend sein. Sie können einen Zeilenwechsel erzwingen indem sie entweder ein zusätliches Leerzeichen hinter ?> einfügen oder explizit mit echo oder print ein Zeilenwechselzeichen am ende ihres Codes ausgeben.

Hinweis: Anmerkung zu Text-Editoren
Es gibt eine ganze Reihe von Text-Editoren und Integrated Development Environments (IDEs), mit denen Sie Ihre PHP-Dateien erstellen, bearbeiten und managen können. Eine Liste solcher Programme finden Sie hier: » PHP Editors List. Wenn Sie einen Editor vorschlagen möchten, besuchen Sie bitte die genannte Seite und bitten Sie den Betreiber der Seite, dass er den Editor der Liste hinzufügt. Wir empfehlen Ihnen einen Editor zu benutzen, der Syntax-Highlighting bietet.

Hinweis: Anmerkung zu Textverarbeitungen
Textverarbeitungen wie StarOffice Writer, Microsoft Word und Abiword sind keine gute Wahl, um PHP-Dateien zu bearbeiten. Wenn Sie eines dieser Programme für dieses Test-Skript nutzen möchten, dann müssen Sie sicherstellen, dass die Datei als "Nur Text"-Datei gespeichert wird, da PHP sonst das Skript nicht lesen und nicht ausführen kann.

Hinweis: Anmerkung zu Notepad, dem Windows-Standard-Editor
Wenn Sie Ihre PHP-Skripte mit Notepad schreiben, müssen Sie sicherstellen, dass Ihre Dateien mit der Endung .php gespeichert werden. (Notepad fügt die Endung .txt automatisch an den Dateinamen an, wenn Sie das nicht mit einem der folgenden Schritte verhindern.) Wenn Sie die Datei speichern und einen Namen für die Datei eingeben sollen, dann setzen Sie den Dateinamen in Anführungszeichen (z.B. "hallo.php"). Alternativ können Sie auch im "Datei speichern"-Fenster in der Drop-Down-Liste "Dateityp" die Einstellung auf "Alle Dateien" ändern. Sie können dann den Dateinamen ohne Anführungszeichen eingeben.

Nachdem Sie jetzt erfolgreich ein einfaches, funktionierendes PHP-Skript geschrieben haben, wird es Zeit, das berühmteste PHP-Skript zu schreiben. Rufen Sie die Funktion phpinfo() auf und Sie bekommen viele nützliche Informationen über Ihr System und Ihre Installation wie z.B. die verfügbaren vordefinierten Variablen, die geladenen PHP-Module und die Konfigurations-Einstellungen. Nehmen Sie sich etwas Zeit und schauen Sie sich diese wichtigen Informationen an.

Beispiel #2 Hole Systeminformationen mit PHP

<?php phpinfo(); ?>



Nützliches

Kommen wir nun zu einem etwas nützlicheren Beispiel. Wir wollen prüfen, welchen Browser der Besucher benutzt. Um das zu tun, prüfen wir den "user agent"-String, den der Browser als Teil seiner HTTP-Anforderung sendet. Diese Information ist in einer Variablen abgelegt. In PHP beginnen Variablen immer mit einem Dollar-Zeichen. Die Variable, die uns jetzt interessiert, ist $_SERVER['HTTP_USER_AGENT'].

Hinweis: $_SERVER ist eine speziell reservierte PHP-Variable, die alle Informationen über den Webserver enthält. Diese Variable wird auch als superglobal bezeichnet. Mehr Informationen darüber Sie auf der Manual-Seite über Superglobals. Diese speziellen Variablen wurden in PHP » 4.1.0 eingeführt. Vorher wurden stattdessen die älteren $HTTP_*_VARS-Arrays benutzt, also z.B. $HTTP_SERVER_VARS. Auch wenn diese Variablen nicht mehr genutzt werden sollen - sie existieren weiterhin. (Beachten Sie auch die Seite Alten Code mit neuen PHP-Versionen benutzen.)

Um die Variable auszugeben, schreiben Sie einfach:

Beispiel #1 Variable ausgeben (Array-Element)

<?php
  
echo $_SERVER['HTTP_USER_AGENT'];
?>

Die Ausgabe dieses Beispiel könnte so aussehen:


Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)

Es gibt viele Typen von Variablen. Im obigen Beispiel haben wir ein Array-Element ausgegeben. Arrays können sehr nützlich sein.

$_SERVER ist nur eine von vielen Variablen, die Ihnen automatisch von PHP zur Verfügung gestellt werden. Eine Liste finden Sie auf der Seite Reservierte Variablen im Manual. Eine vollständige Liste können Sie auch bekommen, wenn Sie sich die Ausgabe der phpinfo()-Funktion ansehen, die im Beispiel des vorigen Abschnitts benutzt wurde.

Sie können mehrere PHP-Anweisungen innerhalb eines PHP-Tags platzieren und so kleine Code-Blöcke schreiben, die mehr als nur eine Ausgabe mit echo() enthalten. Wenn wir zum Beispiel prüfen möchten, ob es sich beim Browser des Besuchers um den Internet Explorer handelt, können wir folgenden Code benutzen:

Beispiel #2 Beispiel, das Kontrollstrukturen und Funktionen benutzt

<?php
if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== FALSE) {
    echo 
"Sie benutzen Microsofts Internet Explorer.<br />";
}
?>

Die Ausgabe dieses Skripts könnte so aussehen:

Sie benutzen Microsofts Internet Explorer.<br />

Hier haben wir Ihnen eine ganze Reihe von neuen Konzepten vorgestellt. Wir haben hier zuerst eine if-Anweisung. Wenn Sie mit der Grundlagen-Syntax von der Programmiersprache C vertraut sind, sollte Ihnen dies logisch erscheinen. Andernfalls sollten Sie sich ein Buch mit einer PHP-Einführung besorgen und die ersten Kapitel lesen. Sie können natürlich auch in die Sprachreferenz des Manuals schauen.

Das zweite hier vorgestellte Konzept ist der Aufruf der Funktion strpos(). strpos() ist eine in PHP eingebaute Funktion, die nach einem String in einem anderen String sucht. In diesem Fall suchen wir nach 'MSIE' (die so genannte Nadel, engl. needle) in $_SERVER['HTTP_USER_AGENT'] (der so genannte Heuhaufen, engl. haystack). Wenn die Nadel im Hauhaufen gefunden wird, gibt die Funktion die Position der Nadel relativ zum Start des Heuhaufens zurück. Andernfalls wird FALSE zurückgegeben. Wenn nicht FALSE zurückgeben wird, wird die if-Anweisung zu TRUE ausgewertet und der Code innerhalb der geschweiften Klammern wird ausgeführt. Andernfalls wird der Code innerhalb der Klammern nicht ausgeführt. Probieren Sie weitere ähnliche Beispiele mit if, else und anderen Funktionen wie strtoupper() oder strlen(). Jede dieser Manual-Seiten enthält weitere Beispiele. Wenn Sie unsicher sind, wie die Funktionen benutzt werden, dann lesen Sie die Handbuch-Seite Wie sind Funktionsdefinitionen (Prototypen) zu lesen? und den Abschnitt zu den PHP-Funktionen.

Wir können jetzt einen Schritt weitergehen und sehen, wie Sie innerhalb eines PHP-Blocks den PHP-Modus verlassen und wieder in ihn hinein gelangen können:

Beispiel #3 HTML- und PHP-Modus vermischt

<?php
if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== FALSE) {
?>
<h3>strpos() muss nicht false zurückgegeben haben</h3>
<p>Sie benutzen Microsofts Internet Explorer.</p>
<?php
} else {
?>
<h3>strstr muss false zurückgegeben haben</h3>
<p>Sie benutzen nicht Microsofts Internet Explorer.</p>
<?php
}
?>

Die Ausgabe dieses Skripts könnte so aussehen:

<h3>strpos() muss nicht false zurückgegeben haben</h3>
<p>Sie benutzen Microsofts Internet Explorer.</p>

Anstatt die PHP echo-Anweisung für die Ausgabe zu benutzen, haben wir den PHP-Modus verlassen und normales HTML verwendet. Der wichtige Punkt hierbei ist, dass der logische Ablauf des Skripts dadurch nicht gestört wird. Nur einer der beiden HTML-Blöcke wird ausgegeben - abhängig davon, was strstr() zurückgibt bzw. ob der String MSIE gefunden wird oder nicht.



Formulare verarbeiten

Eine der mächtigsten Funktionen von PHP ist die Art, wie HTML-Formulare verarbeitet werden. Sie sollten wissen, dass jedes Element eines Formulars automatisch in Ihren PHP-Skripts verfügbar ist. Bitte lesen Sie die Seite Variablen aus externen Quellen für weitere Informationen und Beispiele über das Benutzen von Formularen mit PHP. Hier ist ein Beispiel-HTML-Formular:

Beispiel #1 Ein einfaches HTML-Formular

<form action="action.php" method="post">
 <p>Ihr Name: <input type="text" name="name" /></p>
 <p>Ihr Alter: <input type="text" name="alter" /></p>
 <p><input type="submit" /></p>
</form>

An diesem Formular ist nichts Besonderes. Es ist ein normales HTML-Formular ohne irgendwelche speziellen Tags. Wenn der Benutzer das Formular ausfüllt und den Submit-Button anklickt, wird die Seite action.php aufgerufen. Diese Datei könnte so aussehen:

Beispiel #2 Daten des Formulars ausgeben

Hallo <?php echo $_POST['name']; ?>.
Sie sind <?php echo $_POST['alter']; ?> Jahre alt.

Hallo <?php echo htmlspecialchars($_POST['name']); ?>.
Sie sind <?php echo (int)$_POST['alter']; ?> Jahre alt.

Die Ausgabe des Skripts könnte dann so aussehen:

Hallo Joe.
Sie sind 22 Jahre alt.

Abgesehen von dem htmlspecialchars()-Aufruf und dem (int) Cast sollte einfach zu verstehen sein was hier geschieht. htmlspecialchars() stellt sicher das das Zeichen die in HTML eine spezielle Bedeutung haben ordentlich codiert werden so das niemand HTML Tags oder Javascript-Code in ihre Seite einschmuggeln kann. Da wir wissen das das "alter" Feld eine Zahl enthalten soll konvertieren wir es in einen integer Wert wodurch automatisch überflüssige Zeichen entfernt werden. Sie können diese Aufgabe auch PHP überlassen indem sie die Filter Extension benutzen. Die Variablen $_POST['name'] und $_POST['alter'] werden für Sie automatisch von PHP gesetzt. Weiter oben haben wir das superglobale Array $_SERVER eingeführt, jetzt benutzen wir hier das - ebenfalls superglobale - Array $_POST, dass alle POST-Daten enthält. Beachten Sie, dass die im Formular verwendete Methode POST ist. Hätten wir GET verwendet, dann wären die Daten unseres Formulars stattdessen im superglobalen Array $_GET verfügbar. Sie können auch das superglobale Array $_REQUEST benutzen, wenn die Quelle der Daten keine Rolle spielt. Dieses Array enthält die GET-, POST- und COOKIE-Daten. Beachten Sie auch die import_request_variables()-Funktion.

Sie können auch die Eingaben von XForms in PHP verarbeiten, auch wenn Ihnen die gut von PHP unterstützten HTML-Formulare bisher gereicht haben. Auch wenn die Arbeit mit XForms nichts für Anfänger ist, sind vielleicht trotzdem daran interessant. In unserem Features-Kapitel finden Sie eine kurze Einführung in die Verarbeitung von XForms-Daten.



Alten Code mit neuen PHP-Versionen benutzen

Dadurch dass PHP eine immer beliebtere Skriptsprache ist, gibt es immer mehr öffentliche Quellen und Bibliotheken mit Code, den Sie wieder verwenden können. Die PHP-Entwickler haben versucht, den größten Teil der Sprache abwärtskompatibel zu halten. Das bedeutet, dass ein Skript, das für eine ältere PHP-Version geschrieben wurde, (im Idealfall) ohne Änderungen auch unter einer neueren PHP-Version läuft. In der Praxis sind aber meist einige Änderungen nötig.

Zwei der wichtigsten aktuellen Änderungen, die alten Code betreffen, sind:

  • Die Missbilligung der alten $HTTP_*_VARS-Arrays (die global gemacht werden mussten, wenn man sie innerhalb einer Funktion nutzen wollte). Die folgenden Superglobalen Arrays wurden in PHP » 4.1.0 eingeführt: $_GET, $_POST, $_COOKIE, $_SERVER, $_FILES, $_ENV, $_REQUEST und $_SESSION. Die älteren $HTTP_*_VARS-Arrays, wie $HTTP_POST_VARS, existierten nach wie vor. Seit PHP 5.0.0 können Sie die Registrierung der langen von PHP vordefinierten Arrays mit der Konfigurationsoption register_long_arrays abschalten.
  • Externe Variablen werden standardmäßig nicht mehr im globalen Namensraum registriert. Mit anderen Worten, seit PHP » 4.2.0 ist off die Standard-Einstellung für die PHP-Direktive register_globals. Die empfohlene Methode, auf diese Werte zuzugreifen, ist, die oben genannten superglobalen Arrays zu verwenden. Ältere Skripte, Bücher und Tutorials gehen eventuell davon aus, dass diese Einstellung auf on steht. Wäre die Einstellung z.B. on, dann wäre die Variable $id aus dem URL http://www.example.com/foo.php?id=42 verfügbar. Unabhängig davon, ob on oder off, ist immer $_GET['id'] verfügbar.

Für weitere Details über diese Änderungen siehe die Seite über vordefinierte Variablen und die Links dort.



Und weiter?

Mit dem neuen Wissen sollte es Ihnen möglich sein, das meiste aus diesem Manual und die vielen Beispiel-Skripte in den Beispiel-Archiven zu verstehen. Sie können weitere auf den php.net-Seiten verfügbare Beispiele auf der folgenden Seite finden: » http://www.php.net/links.php.

Wenn Sie an verschiedenen Präsentationen, die Ihnen zeigen, was PHP alles tun kann, interessiert sind, dann besuchen Sie doch folgende Seite: » http://talks.php.net/.





Installation und Konfiguration


Generelle Überlegungen

Bevor Sie mit der Installation beginnen, sollten Sie wissen, für was Sie PHP verwenden wollen. Es gibt drei Hauptbereiche, in denen Sie PHP verwenden können, die im Abschnitt Was kann PHP? beschrieben werden:

  • Webseiten und Webapplikationen (serverseitiges Skripting)
  • Kommandozeilenskripte
  • Desktop(GUI-)Anwendungen

Für die erste und gebräuchlichste Variante brauchen Sie drei Dinge: PHP selbst, einen Webserver und einen Webbrowser. Sie haben wahrscheinlich bereits einen Webbrowser und, abhängig von Ihrem Betriebssystem, möglicherweise ebenso bereits einen Webserver (z.B. Apache auf Linux oder Mac OS X; IIS auf Windows). Sie können ebenfalls Webspace bei einem Unternehmen mieten. Auf diese Weise müssen Sie selbst nichts einrichten und müssen nur PHP-Skripte schreiben, diese auf den gemieteten Server hochladen und die Ergebnisse im Browser betrachten.

Für den Fall, dass Sie den Server und PHP selbst aufsetzen, haben Sie zwei Auswahlmöglichkeiten, um PHP mit dem Server zu verbinden. Für viele Server bietet PHP eine direkte Schnittstelle (auch SAPI genannt). Unter diesen Servern befinden sich Apache, Microsoft Internet Information Server, Netscape und iPlanet Server. Viele andere Server unterstützen ISAPI, die Microsoft Modulschnittstelle (z.B. OmniHTTPd). Falls PHP kein Modul für Ihren Webserver anbietet, können Sie es noch immer als CGI- oder FastCGI-Prozessor verwenden. Das bedeutet, Sie setzen Ihren Server so auf, dass er die ausführbare Datei für CGI von PHP verwendet, um alle Anfragen nach PHP Dateien auf dem Server zu verarbeiten.

Falls Sie außerdem darin interessiert sind, PHP für Kommandozeilenskripte zu verwenden (z.B. Skripte schreiben, die automatisch offline Bilder erzeugen oder Textdateien abhängig von einigen übergebenen Parametern zu verarbeiten), benötigen Sie die ausführbare Datei für die Kommandozeile. Für mehr Informationen lesen Sie bitte den Abschnitt über PHP auf der Kommandozeile. In diesem Fall benötigen Sie weder einen Server noch einen Browser.

Mit PHP können Sie ebenfalls grafische Desktopanwendungen mittels der PHP-GTK-Erweiterung schreiben. Dies erfordert einen völlig anderen Ansatz als das Verfassen von Webseiten, da man kein HTML ausgibt, sondern Fenster und darin enthaltene Objekte verwaltet. Für mehr Informationen zu PHP-GTK werfen Sie bitte einen Blick auf » diese Seite über die Erweiterung. PHP-GTK ist nicht in den offiziellen PHP-Paketen enthalten.

Von jetzt an behandelt dieser Abschnitt nur noch die Installation von PHP für Webserver auf Unix und Windows mittels Serverschnittstellen und CGI. Sie werden außerdem in den folgenden Abschnitten Informationen über die ausführbare Datei für die Kommandozeile finden.

Den PHP-Quellcode und die -Binärpakete für Windows finden Sie unter » http://www.php.net/downloads.php. Wir empfehlen, den Ihnen am nächsten gelegenen » gespiegelten Server für den Download zu verwenden.



Installation auf Unix-Systemen

Inhaltsverzeichnis

Dieser Abschnitt leitet Sie durch die generelle Konfiguration und Installation von PHP auf Unix-Systemen. Bitte lesen Sie zuerst alle Abschnitte, die speziell für Ihre Plattform oder Ihren Webserver zugeschnitten sind, bevor Sie mit dem Installationsprozess beginnen.

Wie dieses Handbuch im Abschnitt Generelle Installationsüberlegungen darlegt, behandeln wir hauptsächlich die web-zentrierten Einrichtungen von PHP, obwohl wir die Installation von PHP für die Kommandozeilennutzung ebenso beschreiben.

Es gibt veschiedene Wege, PHP auf Unix-Plattformen zu installieren: Entweder mit einem Kompilierungs- und Konfigurierungsprozess oder durch verschiedene Methoden von vorgefertigten Paketen. Diese Dokumentation richtet ihr Augenmerk hauptsächlich auf den Prozess des Selbstkompilierens und -konfigurierens von PHP. Viele unix-artige Systeme haben eine Art von Paketinstallationssystem. Dies kann beim Aufsetzen einer Standardkonfiguration helfen, aber wenn Sie eine davon abweichende Menge an Features benötigen (etwa sichere Server oder andere Datenbanktreiber), könnte es sein, dass Sie PHP und/oder Ihren Webserver selbst bauen müssen. Falls Ihnen das Bauen und Kompilieren von Software nicht geläufig ist, ist es lohnenswert zu prüfen, ob bereits jemand ein PHP-Paket mit den von Ihnen benötigten Features gebaut hat.

Folgende Fähigkeiten und Software benötigen Sie für die Kompilierung:

  • Grundlegende Unix-Fertigkeiten (die Fähigkeit, "make" und einen C- Kompiler zu bedienen)
  • Ein ANSI-C-Compiler
  • flex: Version 2.5.4
  • bison: Version 1.28 (bevorzugt), 1.35, or 1.75
  • Ein Webserver
  • Modulspezifische Komponenten (wie GD, PDF-Bibliotheken usw.)

Der anfängliche PHP Setup- und Konfigurationsprozess wird durch die Verwendung von Kommandozeilenoptionenn des configure-Skriptes gesteuert. Sie sollten eine Liste von allen verfügbaren Optionen zusammen mit einer kurzen Erläuterung durch den Aufruf von ./configure --help erhalten. Unser Handbuch dokumentiert die verschiedenen Optionen einzeln. Sie finden die grundlegenden Optionen im Anhang, während die verschiedenen extensionspezifischen Optionen auf den Referenzseiten der Erweiterungen beschrieben sind.

Sobald PHP konfiguriert ist, sind Sie bereit, die Module und/oder die ausführbaren Dateien zu bauen. Der Befehl make sollte sich darum kümmern. Falls dies fehlschlägt und Sie nicht herausfinden können wieso, werfen Sie einen Blick in den Abschnitt Probleme.


Apache 1.3.x auf Unix-Systemen

Dieser Abschnitt beinhaltet Hinweise und Tipps, die sich auf die Installation von PHP speziell für Apache auf Unix-Plattformen beziehen. Wir haben Anweisungen und Hinweise für Apache 2 auf einer eigenen Seite.

Die Anweisungen, die Sie zum unten in Zeile 10 abgebildeten configure-Aufruf hinzufügen können, können Sie aus der Liste von grundlegenden Configure-Optionen und aus den für Erweiterungen spezifiscen Optionen, die auf den jeweiligen Handbuchseiten beschrieben sind, auswählen. Um sicherzustellen, dass die Anweisungen nicht inkorrekt sind, wurden Versionsnummern hier ausgelassen. Sie müssen die Zeichenkette 'xxx' hier mit den zu Ihren Dateien passenden Werten ersetzen.

Beispiel #1 Installationsanweisungen (Apache Shared Module Version) für PHP

1.  gunzip apache_xxx.tar.gz
2.  tar -xvf apache_xxx.tar
3.  gunzip php-xxx.tar.gz
4.  tar -xvf php-xxx.tar
5.  cd apache_xxx
6.  ./configure --prefix=/www --enable-module=so
7.  make
8.  make install
9.  cd ../php-xxx

10. Konfigurieren Sie jetzt Ihr PHP. Dies ist die Stelle, an der Sie
    Ihr PHP mit verschiedenen Optionen, z.B. welche Erweiterungen aktiviert
    sein werden, anpassen können. Rufen Sie ./configure --help für eine Liste
    von verfügbaren Optionen auf. In unseren beispiel werden wir eine einfache
    Konfiguration mit Unterstützung für Apache 1 und MySQL vornehmen. Ihr
    Pfad zu apxs könnte von unserem Beispiel abweichen.

      ./configure --with-mysql --with-apxs=/www/bin/apxs

11. make
12. make install

    Falls Sie sich entscheiden, die Werte Ihrer Konfiguration nach der
    Installation zu ändern, müssen Sie nur die letzten drei Schritte
    wiederholen. Sie müssen nur Apache neu starten, damit das neue Modul
    aktiv wird. Eine erneute Kompilation von Apache ist nicht erforderlich.

    Beachten Sie, dass 'make install', falls nicht anders angewiesen,
    ebenfalls PEAR, verschiedene PHP-Tools wie phpize, das PHP CLI und mehr
    installieren wird.

13. Ihre php.ini Datei einrichten:

      cp php.ini-dist /usr/local/lib/php.ini

    Sie können Ihre .ini-Datei bearbeiten, um verschiedene PHP-Einstellungen
    vorzunehmen. Wenn Sie es bevorzugen, Ihre php.ini-Datei an anderer
    Stelle zu haben, verwenden Sie --with-config-file-path=/irgendein/pfad
    in Schritt 10.
    
    Wenn Sie stattdessen php.ini-recommended auswählen stellen Sie sicher,
    dass Sie die enthaltenen Änderungen lesen, da diese sich auf das Verhalten
    von PHP auswirken.

14. Ändern Sie Ihre httpd.conf-Datei, damit das PHP-Modul geladen wird. Der
    Pfad auf der rechten Seite des LoadModule Befehls muss zum Pfad des
    PHP-Moduls auf Ihrem System zeigen. Das 'make install' von oben könnte
    dies bereits für Sie hinzugefügt haben, aber prüfen Sie dies nach.

    Für PHP 4:
            
      LoadModule php4_module libexec/libphp4.so

    Für PHP 5:
                      
      LoadModule php5_module libexec/libphp5.so
      
15. Fügen Sie dies im AddModule-Abschnitt Ihrer httpd.conf, irgendwo unterhalb
    von ClearModuleList, hinzu:
    
    Für PHP 4:
    
      AddModule mod_php4.c
      
    Für PHP 5:
    
      AddModule mod_php5.c

16. Sagen Sie Ihrem Apache, bestimmte Dateiendungen als PHP zu parsen. Zum 
    Beispiel lassen wir die .php-Dateiendung als PHP behandeln. Sie können
    jede Erweiterung als PHP parsen lassen, indem Sie einfach weitere
    Endungen, jeweils durch ein Leerzeichen getrennt, hinzufügen. Wir fügen
    .phtml hinzu, um dies vorzuführen. 

      AddType application/x-httpd-php .php .phtml

    Es ist weiterhin üblich, die .phps-Dateiendung zu konfigurieren, damit
    diese farblich hervorgehobenen Quellcode anzeigt. Dies kann wie folgt
    eingerichtet werden:
    
      AddType application/x-httpd-php-source .phps

17. Verwenden Sie Ihre normale Prozedur, um den Apache zu starten. (Sie müssen
    den Server anhalten und neu starten, nicht nur ein erneutes laden des
    Servers mittels eines HUP- oder USR1-Signals veranlassen.)

Alternativ, um PHP als statisches Objekt zu installieren:

Beispiel #2 Installationsanweisungen (Statische Modulinstallation für Apache) für PHP

1.  gunzip -c apache_1.3.x.tar.gz | tar xf -
2.  cd apache_1.3.x
3.  ./configure
4.  cd ..

5.  gunzip -c php-5.x.y.tar.gz | tar xf -
6.  cd php-5.x.y
7.  ./configure --with-mysql --with-apache=../apache_1.3.x
8.  make
9.  make install

10. cd ../apache_1.3.x

11. ./configure --prefix=/www --activate-module=src/modules/php5/libphp5.a
    (Die obige Zeile ist korrekt! Ja, wir wissen, dass libphp5.a zu diesem
    Zeitpunkt nicht existiert. Das soll sie auch noch nicht. Sie wird
    angelegt werden.)

12. make
    (Sie sollten jetzt eine ausführbare Datei httpd haben, welche Sie in Ihr
    Apache-Binärverezichnis kopieren können. Wenn dies Ihre Erstinstallation
    ist, müssen Sie außerdem noch "make install" aufrufen)

13. cd ../php-5.x.y
14. cp php.ini-dist /usr/local/lib/php.ini

15. Sie können /usr/local/lib/php.ini bearbeiten, um PHP-Einstellungen zu
    ändern. Bearbeiten Sie Ihre httpd.conf oder srm.conf-Datei und fügen Sie
    folgendes hinzu:

    AddType application/x-httpd-php .php

Hinweis: Ersetzen Sie php-5 durch php-4 und php5 durch php4 in PHP4.

Abhängig von Ihrer Apacheinstallation und Unixvariante gibt es viele verschiedene Methoden, um den Server anzuhalten und erneut zu starten. Unten sind für verschiedene Apache/Unix-Installationen einige typische Zeilen zum Neustart des Servers. Sie sollten /path/to mit dem Pfad dieser Anwendungen auf Ihrem System ersetzen.

Beispiel #3 Beispielbefehle, um Apache neu zu starten

1. Verschiedene Linux- und SysV-Varianten:
/etc/rc.d/init.d/httpd restart

2. Verwendung der apachectl Skripte:
/path/to/apachectl stop
/path/to/apachectl start

3. httpdctl und httpsdctl (mit OpenSSL), ähnlich wie apachectl:
/path/to/httpsdctl stop
/path/to/httpsdctl start

4. Mit mod_ssl oder einem anderen SSL Server, könnten Sie manuell stoppen
   und starten wollen:
/path/to/apachectl stop
/path/to/apachectl startssl

Die Orte der apachectl- und http(s)dctl-Binärdateien sind häufig verschieden. Wenn Ihr System einen locate-, whereis- oder which-Befehl besitzt, können diese Ihnen beim Auffinden des Serverkontrollprogrammes helfen.

Verschiedene Beispiele zur Kompilierung von PHP für Apache wie folgt:

./configure --with-apxs --with-pgsql

Dies wird eine Bibliothek libphp5.so (oder libphp4.so in PHP4) erzeugen, die mittels einer LoadModule-Zeile in der httpd.conf des Apache geladen wird. PostgreSQL-Unterstützung ist in diese Bibliothek eingebaut.

./configure --with-apxs --with-pgsql=shared

Dies wird eine Bibliothek libphp4.so für Apache erzeugen, aber ebenso eine pgsql.so, die von PHP mit der Extension-Direktive in der php.ini-Datei oder durch explizites Laden in einem Skript mittels der Funktion dl() geladen wird.

./configure --with-apache=/path/to/apache_source --with-pgsql

Dies wird eine Bibliothek libmodphp5.a, eine mod_php5.c und einige zugehörige Dateien erzeugen und diese in das Verzeichnis src/modules/php5 des Apache Quellcodes kopieren. Kompilieren Sie danach Apache mit --activate-module=src/modules/php5/libphp5.a und das Apache Build System wird eine libphp5.a erzeugen und statisch in die Binärdatei httpd einbinden (ersetzen Sie php5 durch php4 für PHP 4). Unterstützung für PostgreSQL wird in diese httpd Binärdatei mit eingebaut, weshalb das Endergebnis eine einzige Datei namens httpd ist, welche den gesamten Apache und PHP beinhaltet.

./configure --with-apache=/path/to/apache_source --with-pgsql=shared

Genau wie oben, aber anstatt die Unterstützung für PostgreSQL direkt in httpd mit einzubinden wird eine gemeinsam verwendete Bibliothek namens pgsql.so erzeugt, die man mittels der php.ini Datei oder direkt über dl() in PHP einbinden kann.

Wenn Sie aus den verschiedenen Möglichkeiten auswählen, PHP zu kompilieren, sollten Sie die Vor- und Nachteile der jeweiligen Methoden bedenken. Das Erzeugen einer gemeinsam verwendeten Bibliothek resultiert darin, dass man Apache getrennt kompilieren kann und nicht alles erneut kompilieren muss, wenn man etwas zu PHP hinzufügt oder ändert. Das direkte Einbauen in Apache (statisch) bedeutet, dass PHP schneller lädt und schneller läuft. Für weitere Informationen konsultieren Sie die Apache » Webseite zur DSO-Unterstützung.

Hinweis: Apaches mitgelieferte httpd.conf enthält derzeit einen Abschnitt, der wie folgt aussieht:

User nobody
Group "#-1"

Wenn man dies nicht auf "Group nogroup" oder etwas ähnliches ("Group daemon" ist auch üblich) ändert, wird PHP nicht imstande sein, Dateien zu öffnen.

Hinweis: Stellen Sie sicher, dass Sie die installierte Version von apxs angeben, wenn Sie --with-apxs=/path/to/apxs verwenden. Sie dürfen NICHT die apxs-Version angeben, die dem Apache Quellcode beiliegt, sondern jene, die tatsächlich auf Ihrem System installiert ist.



Apache 2.0 auf Unixsystemen

Dieser Abschnitt enthält Hinweise und Tipps, die sich auf die Installation von PHP speziell für Apache 2.0 auf Unixsystemen beziehen.

Warnung

Wir empfehlen, in einer Produktionsumgebung kein Threaded MPM mit Apache2 zu verwenden. Verwenden Sie stattdessen das Prefork MPM oder Apache1. Für weitere Informationen und die Gründe lesen Sie bitte den entsprechenden FAQ-Eintrag über die Verwendung von Apache2 mit Threaded MPM.

Es wird empfohlen, einen Blick auf die » Apache Dokumentation zu werfen, um ein grundlegendes Verständnis des Apache 2.0 Servers zu erhalten.

Hinweis: PHP and Apache 2.0.x compatibility notes
The following versions of PHP are known to work with the most recent version of Apache 2.0.x:

These versions of PHP are compatible to Apache 2.0.40 and later.
Apache 2.0 SAPI-support started with PHP 4.2.0. PHP 4.2.3 works with Apache 2.0.39, don't use any other version of Apache with PHP 4.2.3. However, the recommended setup is to use PHP 4.3.0 or later with the most recent version of Apache2.
All mentioned versions of PHP will work still with Apache 1.3.x.

Laden Sie die aktuellste Version von » Apache 2.0 und eine passende Version von den oben angegebenen Quellen herunter. Dieser Schnelleinstieg behandelt nur die Grundlagen, um mit Apache 2.0 und PHP einzusteigen. Für mehr Informationen lesen Sie bitte die » Apache Dokumentation. Versionsnummern wurden hier ausgelassen, um sicherzustellen, dass die Anweisungen nicht inkorrekt sind. Sie müssen die Zeichenkette 'NN' mit den zu Ihren Dateien passenden Werten ersetzen.

Beispiel #1 Installationsanweisungen (Apache 2 Shared Module Version)

1.  gzip -d httpd-2_0_NN.tar.gz
2.  tar xvf httpd-2_0_NN.tar
3.  gunzip php-NN.tar.gz
4.  tar -xvf php-NN.tar
5.  cd httpd-2_0_NN
6.  ./configure --enable-so
7.  make
8.  make install

    Nun steht Ihnen Apache 2.0.NN unter /usr/local/apache2 zur Verfügung,
    konfiguriert mit Unterstützung für nachladbare Module und dem
    Standard MPM Prefork. Um diese Installation zu testen, verwenden Sie die
    übliche Prozedur, den Apacheserver zu starten, also z.B.:
    /usr/local/apache2/bin/apachectl start
    Stoppen Sie nun den Server, um mit der Konfiguration von PHP fortzusetzen:
    /usr/local/apache2/bin/apachectl stop.

9.  cd ../php-NN

10. Konfigurieren Sie nun Ihr PHP. Dies ist die Stelle, an der Sie Ihr
    PHP mit verschiedenen Optionen, wie etwa installierten Erweiterungen,
    anpassen können. Rufen Sie ./configure --help auf, um eine Liste
    der verfügbaren Optionen zu erhalten. In unserem Beispiel werden
    wir eine einfache Konfiguration mit Unterstützung für Apache 2
    und MySQL erzeugen. Ihr Pfad zu apxs könnte sich unterscheiden,
    tatsächlich könnte das Programm auf Ihrem System auch apxs2 heißen.

      ./configure --with-apxs2=/usr/local/apache2/bin/apxs --with-mysql

11. make
12. make install

    Wenn Sie sich entscheiden, Ihre Konfigurationsoptionen nach der
    Installation zu ändern, müssen Sie nur die letzten drei Schritte
    wiederholen. Sie müssen nur Apache neustarten, damit das neue
    Modul verwendet wird. Eine erneute Kompilierung von Apache ist
    nicht notwendig.

    Beachten Sie, dass, wenn nicht anders erwähnt, 'make install' ebenso
    PEAR und verschiedene PHP Werkzeuge wie phpize, PHP CLI und anderes
    installieren wird.

13. Ihre php.ini einrichten

    cp php.ini-dist /usr/local/lib/php.ini

    Sie können Ihre .ini-Datei ändern, um verschiedene PHP-Optionen zu setzen.
    Wenn Sie die php.ini-Datei an einer anderen Stelle bevorzugen, verwenden
    Sie --with-config-file-path=/some/path in Schritt 10.

    Wenn Sie sich stattdessen für php.ini-recommended entscheiden, stellen Sie
    sicher, dass Sie die darin enthaltene Liste von Änderungen lesen, da diese
    das Verhalten von PHP beeinflussen.

14. Bearbeiten Sie Ihre httpd.conf, um das PHP Modul zu laden. Der Pfad
    auf der rechten Seite der LoadModule-Anweisung muss auf den Ort des
    PHP-Moduls auf Ihrem System zeigen. Das obige make install könnte dies
    bereits für Sie hinzugefügt haben, aber prüfen Sie dies.

    Für PHP 4:

      LoadModule php4_module modules/libphp4.so

    Für PHP 5:

      LoadModule php5_module modules/libphp5.so

15. Weisen Sie Apache an, bestimmte Dateiendungen als PHP Skripte zu behandeln.
    Zum Beispiel werden wir den Apache Dateien mit der Endung .php als PHP
    ausführen lassen. Anstatt nur die Apachedirektive AddType zu verwenden,
    wollen wir zusätzlich verhindern, dass potentiell gefährliche hochgeladene
    und erzeugte Dateien wie exploit.php.jpg als PHP-Dateien ausgeführt werden.
    Wenn Sie dieses Beispiel verwenden, können Sie jede Dateiendung als PHP
    interpretieren lassen, wenn Sie sie einfach hinzufügen. Wir demonstrieren
    dies, indem wir .phtml einfügen.

      <FilesMatch \.php$>
          SetHandler application/x-httpd-php
      </FilesMatch>

    Oder wenn wir erlauben wollen, dass .php, .php2, .php3, .php4, .php5, .php6
    und .phtml und sonst nichts als PHP interpretiert werden, könnten wird
    ein Statement wie dieses verwenden:

      <FilesMatch "\.ph(p[2-6]?|tml)$">
          SetHandler application/x-httpd-php
      </FilesMatch>

    Und um .phps-Dateien als PHP-Quelldateien interpretieren zu lassen, fügen
    wir die folgende Anweisung hinzu:

      <FilesMatch "\.phps$">
          SetHandler application/x-httpd-php-source
      </FilesMatch>

16. Verwenden Sie die übliche Prozedur, um den Apache Server zu starten, z.B.:

      /usr/local/apache2/bin/apachectl start

          - ODER -

      service httpd restart

Wenn Sie den obigen Anweisungen folgen, werden Sie einen laufenden Apache2 mit Unterstützung für PHP als SAPI-Modul erhalten. Natürlich existieren für Apache und PHP viele weitere Konfigurationseinstellungen. Verwenden Sie ./configure --help im jeweiligen Quellcodeverzeichnis, um weitere Informationen zu erhalten. Falls Sie eine Multithreaded-Version von Apache2 bauen wollen, müssen Sie das Standard MPM-Modul prefork entweder durch worker oder perchild ersetzen. Fügen Sie dazu in obigem Schritt 6 an Ihre Konfigurationszeile entweder die Option --with-mpm=worker oder --with-mpm=perchild an. Denken Sie an die daraus reultierenden Konsequenzen und machen Sie sich klar, was Sie damit tun. Für mehr Informationen werfen Sie einen Blick auf die Apache Dokumantation zum Thema » MPM-Module.

Hinweis: Falls Sie Content Negotiation verwenden wollen, lesen Sie die Apache MultiViews FAQ.

Hinweis: Um eine Multithreaded Version von Apache zu erzeugen, muss Ihr System Threads unterstützen. Dies impliziert, dass Sie PHP mit der experimentellen Zend Thread Safety (ZTS) bauen. Deshalb könnten nicht alle Erweiterungen verfügbar sein. Die empfohlene Einstellung ist es, Apache mit dem prefork -MPM-Modul zu bauen.



Lighttpd 1.4 on Unix systems

This section contains notes and hints specific to Lighttpd 1.4 installs of PHP on Unix systems.

Please use the » Lighttpd trac to learn how to install Lighttpd properly before continuing.

Fastcgi is the preferred SAPI to connect PHP and Lighttpd. Fastcgi is automagically enabled in php-cgi in PHP 5.3, but for older versions configure PHP with --enable-fastcgi. To confirm that PHP has fastcgi enabled, php -v should contain PHP 5.2.5 (cgi-fcgi) Before PHP 5.2.3, fastcgi was enabled on the php binary (there was no php-cgi).

Letting Lighttpd spawn php processes

To configure Lighttpd to connect to php and spawn fastcgi processes, edit lighttpd.conf. Sockets are preferred to connect to fastcgi processes on the local system.

Beispiel #1 Partial lighttpd.conf

server.modules += ( "mod_fastcgi" )

fastcgi.server = ( ".php" =>
  ((
    "socket" => "/tmp/php.socket",
    "bin-path" => "/usr/local/bin/php-cgi",
    "bin-environment" => (
      "PHP_FCGI_CHILDREN" => "16",
      "PHP_FCGI_MAX_REQUESTS" => "10000"
    ),
    "min-procs" => 1,
    "max-procs" => 1,
    "idle-timeout" => 20
  ))
)

The bin-path directive allows lighttpd to spawn fastcgi processes dynamically. PHP will spawn children according to the PHP_FCGI_CHILDREN environment variable. The "bin-environment" directive sets the environment for the spawned processes. PHP will kill a child process after the number of requests specified by PHP_FCGI_MAX_REQUESTS is reached. The directives "min-procs" and "max-procs" should generally be avoided with PHP. PHP manages its own children and opcode caches like APC will only share among children managed by PHP. If "min-procs" is set to something greater than 1, the total number of php responders will be multiplied PHP_FCGI_CHILDREN (2 min-procs * 16 children gives 32 responders).

Spawning with spawn-fcgi

Lighttpd provides a program called spawn-fcgi to ease the process of spawning fastcgi processes easier.

Spawning php-cgi

It is possible to spawn processes without spawn-fcgi, though a bit of heavy-lifting is required. Setting the PHP_FCGI_CHILDREN environment var controls how many children PHP will spawn to handle incoming requests. Setting PHP_FCGI_MAX_REQUESTS will determine how long (in requests) each child will live. Here's a simple bash script to help spawn php responders.

Beispiel #2 Spawning FastCGI Responders

#!/bin/sh

# Location of the php-cgi binary
PHP=/usr/local/bin/php-cgi

# PID File location
PHP_PID=/tmp/php.pid

# Binding to an address
#FCGI_BIND_ADDRESS=10.0.1.1:10000
# Binding to a domain socket
FCGI_BIND_ADDRESS=/tmp/php.sock

PHP_FCGI_CHILDREN=16
PHP_FCGI_MAX_REQUESTS=10000

env -i PHP_FCGI_CHILDREN=$PHP_FCGI_CHILDREN \
       PHP_FCGI_MAX_REQUESTS=$PHP_FCGI_MAX_REQUESTS \
       $PHP -b $FCGI_BIND_ADDRESS &

echo $! > "$PHP_PID"

Connecting to remote FCGI instances

Fastcgi instances can be spawned on multiple remote machines in order to scale applications.

Beispiel #3 Connecting to remote php-fastcgi instances

fastcgi.server = ( ".php" =>
   (( "host" => "10.0.0.2", "port" => 1030 ),
    ( "host" => "10.0.0.3", "port" => 1030 ))
)


Caudium

PHP can be built as a Pike module for the » Caudium webserver. Follow the simple instructions below to install PHP for Caudium.

Beispiel #1 Caudium Installation Instructions

1.  Make sure you have Caudium installed prior to attempting to
    install PHP 4. For PHP 4 to work correctly, you will need Pike
    7.0.268 or newer. For the sake of this example we assume that
    Caudium is installed in /opt/caudium/server/.
2.  Change directory to php-x.y.z (where x.y.z is the version number).
3.  ./configure --with-caudium=/opt/caudium/server
4.  make
5.  make install
6.  Restart Caudium if it's currently running.
7.  Log into the graphical configuration interface and go to the
    virtual server where you want to add PHP 4 support.
8.  Click Add Module and locate and then add the PHP 4 Script Support module.
9.  If the documentation says that the 'PHP 4 interpreter isn't
    available', make sure that you restarted the server. If you did
    check /opt/caudium/logs/debug/default.1 for any errors related to
    PHP4.so. Also make sure that 
    caudium/server/lib/[pike-version]/PHP4.so
    is present.
10. Configure the PHP Script Support module if needed.

You can of course compile your Caudium module with support for the various extensions available in PHP 4. See the reference pages for extension specific configure options.

Hinweis: When compiling PHP 4 with MySQL support you must make sure that the normal MySQL client code is used. Otherwise there might be conflicts if your Pike already has MySQL support. You do this by specifying a MySQL install directory the --with-mysql option.



fhttpd related notes

To build PHP as an fhttpd module, answer "yes" to "Build as an fhttpd module?" (the --with-fhttpd=DIR option to configure) and specify the fhttpd source base directory. The default directory is /usr/local/src/fhttpd. If you are running fhttpd, building PHP as a module will give better performance, more control and remote execution capability.

Hinweis: Support for fhttpd is no longer available as of PHP 4.3.0.



Sun, iPlanet and Netscape servers on Sun Solaris

This section contains notes and hints specific to Sun Java System Web Server, Sun ONE Web Server, iPlanet and Netscape server installs of PHP on Sun Solaris.

From PHP 4.3.3 on you can use PHP scripts with the NSAPI module to generate custom directory listings and error pages. Additional functions for Apache compatibility are also available. For support in current web servers read the note about subrequests.

You can find more information about setting up PHP for the Netscape Enterprise Server (NES) here: » http://benoit.noss.free.fr/php/install-php4.html

To build PHP with Sun JSWS/Sun ONE WS/iPlanet/Netscape web servers, enter the proper install directory for the --with-nsapi=[DIR] option. The default directory is usually /opt/netscape/suitespot/. Please also read /php-xxx-version/sapi/nsapi/nsapi-readme.txt.

  1. Install the following packages from » http://www.sunfreeware.com/ or another download site:

    • autoconf-2.13
    • automake-1.4
    • bison-1_25-sol26-sparc-local
    • flex-2_5_4a-sol26-sparc-local
    • gcc-2_95_2-sol26-sparc-local
    • gzip-1.2.4-sol26-sparc-local
    • m4-1_4-sol26-sparc-local
    • make-3_76_1-sol26-sparc-local
    • mysql-3.23.24-beta (if you want mysql support)
    • perl-5_005_03-sol26-sparc-local
    • tar-1.13 (GNU tar)

  2. Make sure your path includes the proper directories PATH=.:/usr/local/bin:/usr/sbin:/usr/bin:/usr/ccs/bin and make it available to your system export PATH .
  3. gunzip php-x.x.x.tar.gz (if you have a .gz dist, otherwise go to 4).
  4. tar xvf php-x.x.x.tar
  5. Change to your extracted PHP directory: cd ../php-x.x.x
  6. For the following step, make sure /opt/netscape/suitespot/ is where your netscape server is installed. Otherwise, change to the correct path and run:

    ./configure --with-mysql=/usr/local/mysql \
    --with-nsapi=/opt/netscape/suitespot/ \
    --enable-libgcc

  7. Run make followed by make install.

After performing the base install and reading the appropriate readme file, you may need to perform some additional configuration steps.

Configuration Instructions for Sun/iPlanet/Netscape

Firstly you may need to add some paths to the LD_LIBRARY_PATH environment for the server to find all the shared libs. This can best done in the start script for your web server. The start script is often located in: /path/to/server/https-servername/start. You may also need to edit the configuration files that are located in: /path/to/server/https-servername/config/.

  1. Add the following line to mime.types (you can do that by the administration server):

    type=magnus-internal/x-httpd-php exts=php
    

  2. Edit magnus.conf (for servers >= 6) or obj.conf (for servers < 6) and add the following, shlib will vary depending on your system, it will be something like /opt/netscape/suitespot/bin/libphp4.so. You should place the following lines after mime types init.

    Init fn="load-modules" funcs="php4_init,php4_execute,php4_auth_trans" shlib="/opt/netscape/suitespot/bin/libphp4.so"
    Init fn="php4_init" LateInit="yes" errorString="Failed to initialize PHP!" [php_ini="/path/to/php.ini"]
    

    (PHP >= 4.3.3) The php_ini parameter is optional but with it you can place your php.ini in your web server config directory.

  3. Configure the default object in obj.conf (for virtual server classes [version 6.0+] in their vserver.obj.conf):

    <Object name="default">
    .
    .
    .
    .#NOTE this next line should happen after all 'ObjectType' and before all 'AddLog' lines
    Service fn="php4_execute" type="magnus-internal/x-httpd-php" [inikey=value inikey=value ...]
    .
    .
    </Object>
    

    (PHP >= 4.3.3) As additional parameters you can add some special php.ini-values, for example you can set a docroot="/path/to/docroot" specific to the context php4_execute is called. For boolean ini-keys please use 0/1 as value, not "On","Off",... (this will not work correctly), e.g. zlib.output_compression=1 instead of zlib.output_compression="On"

  4. This is only needed if you want to configure a directory that only consists of PHP scripts (same like a cgi-bin directory):

    <Object name="x-httpd-php">
    ObjectType fn="force-type" type="magnus-internal/x-httpd-php"
    Service fn=php4_execute [inikey=value inikey=value ...]
    </Object>
    

    After that you can configure a directory in the Administration server and assign it the style x-httpd-php. All files in it will get executed as PHP. This is nice to hide PHP usage by renaming files to .html.

  5. Setup of authentication: PHP authentication cannot be used with any other authentication. ALL AUTHENTICATION IS PASSED TO YOUR PHP SCRIPT. To configure PHP Authentication for the entire server, add the following line to your default object:

    <Object name="default">
    AuthTrans fn=php4_auth_trans
    .
    .
    .
    </Object>
    

  6. To use PHP Authentication on a single directory, add the following:

    <Object ppath="d:\path\to\authenticated\dir\*">
    AuthTrans fn=php4_auth_trans
    </Object>
    

Hinweis: The stacksize that PHP uses depends on the configuration of the web server. If you get crashes with very large PHP scripts, it is recommended to raise it with the Admin Server (in the section "MAGNUS EDITOR").

CGI environment and recommended modifications in php.ini

Important when writing PHP scripts is the fact that Sun JSWS/Sun ONE WS/iPlanet/Netscape is a multithreaded web server. Because of that all requests are running in the same process space (the space of the web server itself) and this space has only one environment. If you want to get CGI variables like PATH_INFO, HTTP_HOST etc. it is not the correct way to try this in the old PHP way with getenv() or a similar way (register globals to environment, $_ENV). You would only get the environment of the running web server without any valid CGI variables!

Hinweis: Why are there (invalid) CGI variables in the environment?
Answer: This is because you started the web server process from the admin server which runs the startup script of the web server, you wanted to start, as a CGI script (a CGI script inside of the admin server!). This is why the environment of the started web server has some CGI environment variables in it. You can test this by starting the web server not from the administration server. Use the command line as root user and start it manually - you will see there are no CGI-like environment variables.

Simply change your scripts to get CGI variables in the correct way for PHP 4.x by using the superglobal $_SERVER. If you have older scripts which use $HTTP_HOST, etc., you should turn on register_globals in php.ini and change the variable order too (important: remove "E" from it, because you do not need the environment here):

variables_order = "GPCS"
register_globals = On

Special use for error pages or self-made directory listings (PHP >= 4.3.3)

You can use PHP to generate the error pages for "404 Not Found" or similar. Add the following line to the object in obj.conf for every error page you want to overwrite:

Error fn="php4_execute" code=XXX script="/path/to/script.php" [inikey=value inikey=value...]

where XXX is the HTTP error code. Please delete any other Error directives which could interfere with yours. If you want to place a page for all errors that could exist, leave the code parameter out. Your script can get the HTTP status code with $_SERVER['ERROR_TYPE'].

Another possibility is to generate self-made directory listings. Just create a PHP script which displays a directory listing and replace the corresponding default Service line for type="magnus-internal/directory" in obj.conf with the following:

Service fn="php4_execute" type="magnus-internal/directory" script="/path/to/script.php" [inikey=value inikey=value...]

For both error and directory listing pages the original URI and translated URI are in the variables $_SERVER['PATH_INFO'] and $_SERVER['PATH_TRANSLATED'].

Note about nsapi_virtual() and subrequests (PHP >= 4.3.3)

The NSAPI module now supports the nsapi_virtual() function (alias: virtual()) to make subrequests on the web server and insert the result in the web page. This function uses some undocumented features from the NSAPI library. On Unix the module automatically looks for the needed functions and uses them if available. If not, nsapi_virtual() is disabled.

Hinweis: But be warned: Support for nsapi_virtual() is EXPERIMENTAL!!!



CGI and command line setups

The default is to build PHP as a CGI program. This creates a command line interpreter, which can be used for CGI processing, or for non-web-related PHP scripting. If you are running a web server PHP has module support for, you should generally go for that solution for performance reasons. However, the CGI version enables users to run different PHP-enabled pages under different user-ids.

Warnung

Wenn Sie das CGI-Setup verwenden, ist Ihr Server für einige mögliche Angriffe anfällig. Wie Sie sich vor diesen Angriffen schützen können, entnehmen Sie bitte dem Kapitel über CGI-Sicherheit.

As of PHP 4.3.0, some important additions have happened to PHP. A new SAPI named CLI also exists and it has the same name as the CGI binary. What is installed at {PREFIX}/bin/php depends on your configure line and this is described in detail in the manual section named Using PHP from the command line. For further details please read that section of the manual.

Testing

If you have built PHP as a CGI program, you may test your build by typing make test. It is always a good idea to test your build. This way you may catch a problem with PHP on your platform early instead of having to struggle with it later.

Using Variables

Some server supplied environment variables are not defined in the current » CGI/1.1 specification. Only the following variables are defined there: AUTH_TYPE, CONTENT_LENGTH, CONTENT_TYPE, GATEWAY_INTERFACE, PATH_INFO, PATH_TRANSLATED, QUERY_STRING, REMOTE_ADDR, REMOTE_HOST, REMOTE_IDENT, REMOTE_USER, REQUEST_METHOD, SCRIPT_NAME, SERVER_NAME, SERVER_PORT, SERVER_PROTOCOL, and SERVER_SOFTWARE. Everything else should be treated as 'vendor extensions'.



HP-UX specific installation notes

This section contains notes and hints specific to installing PHP on HP-UX systems.

There are two main options for installing PHP on HP-UX systems. Either compile it, or install a pre-compiled binary.

Official pre-compiled packages are located here: » http://software.hp.com/

Until this manual section is rewritten, the documentation about compiling PHP (and related extensions) on HP-UX systems has been removed. For now, consider reading the following external resource: » Building Apache and PHP on HP-UX 11.11



OpenBSD installation notes

This section contains notes and hints specific to installing PHP on » OpenBSD 3.6.

Using Binary Packages

Using binary packages to install PHP on OpenBSD is the recommended and simplest method. The core package has been separated from the various modules, and each can be installed and removed independently from the others. The files you need can be found on your OpenBSD CD or on the FTP site.

The main package you need to install is php4-core-4.3.8.tgz, which contains the basic engine (plus gettext and iconv). Next, take a look at the module packages, such as php4-mysql-4.3.8.tgz or php4-imap-4.3.8.tgz. You need to use the phpxs command to activate and deactivate these modules in your php.ini.

Beispiel #1 OpenBSD Package Install Example

# pkg_add php4-core-4.3.8.tgz
# /usr/local/sbin/phpxs -s
# cp /usr/local/share/doc/php4/php.ini-recommended /var/www/conf/php.ini
  (add in mysql)
# pkg_add php4-mysql-4.3.8.tgz
# /usr/local/sbin/phpxs -a mysql
  (add in imap)
# pkg_add php4-imap-4.3.8.tgz
# /usr/local/sbin/phpxs -a imap
  (remove mysql as a test)
# pkg_delete php4-mysql-4.3.8
# /usr/local/sbin/phpxs -r mysql
  (install the PEAR libraries)
# pkg_add php4-pear-4.3.8.tgz

Read the » packages(7) manual page for more information about binary packages on OpenBSD.

Using Ports

You can also compile up PHP from source using the » ports tree. However, this is only recommended for users familiar with OpenBSD. The PHP 4 port is split into two sub-directories: core and extensions. The extensions directory generates sub-packages for all of the supported PHP modules. If you find you do not want to create some of these modules, use the no_* FLAVOR. For example, to skip building the imap module, set the FLAVOR to no_imap.

Common Problems

  • The default install of Apache runs inside a » chroot(2) jail, which will restrict PHP scripts to accessing files under /var/www. You will therefore need to create a /var/www/tmp directory for PHP session files to be stored, or use an alternative session backend. In addition, database sockets need to be placed inside the jail or listen on the localhost interface. If you use network functions, some files from /etc such as /etc/resolv.conf and /etc/services will need to be moved into /var/www/etc. The OpenBSD PEAR package automatically installs into the correct chroot directories, so no special modification is needed there. More information on the OpenBSD Apache is available in the » OpenBSD FAQ.
  • The OpenBSD 3.6 package for the » gd extension requires XFree86 to be installed. If you do not wish to use some of the font features that require X11, install the php4-gd-4.3.8-no_x11.tgz package instead.

Older Releases

Older releases of OpenBSD used the FLAVORS system to compile up a statically linked PHP. Since it is hard to generate binary packages using this method, it is now deprecated. You can still use the old stable ports trees if you wish, but they are unsupported by the OpenBSD team. If you have any comments about this, the current maintainer for the port is Anil Madhavapeddy (avsm at openbsd dot org).



Solaris specific installation tips

This section contains notes and hints specific to installing PHP on Solaris systems.

Required software

Solaris installs often lack C compilers and their related tools. Read this FAQ for information on why using GNU versions for some of these tools is necessary. The required software is as follows:

  • gcc (recommended, other C compilers may work)
  • make
  • flex
  • bison
  • m4
  • autoconf
  • automake
  • perl
  • gzip
  • tar
  • GNU sed

In addition, you will need to install (and possibly compile) any additional software specific to your configuration, such as Oracle or MySQL.

Using Packages

You can simplify the Solaris install process by using pkgadd to install most of your needed components.



Debian GNU/Linux Installationshinweise

Dieser Abschnitt beinhaltet Hinweise und Tipps die sich auf die Installation von PHP speziell auf » Debian GNU/Linux beziehen.

APT verwenden

Während Sie einfach den PHP Quellcode herunterladen und selbst kompilieren können ist die einfachste und sauberste Methode der Installation die Verwendung von Debians Paketmanagementsystem. Falls Sie nicht mit dem Bau von Software unter Linux vertraut sind, ist dies die beste Möglichkeit.

Die erste Entscheidung, die Sie treffen müssen, ist, ob Sie Apache 1.3.x oder Apache 2.x installieren wollen. Die entsprechenden PHJP Pakete sind dementsprechend libapache-mod-php* und libapache2-mod-php* benannt. Die unten angegebenen Schritte werden Apache 1.3.x verwenden. Bitte beachten Sie, dass zum Zeitpunkt des Schreibens kein offizielles PHP 5 Paket für Debian existiert. Daher werden die unten angegebenen Schritte PHP 4 installieren.

PHP ist in Debian ebenfalls als CGI und CLI varianten verfügbar, entsprechend php4-cgi und php4-cli benannt. Wenn Sie diese benötigen, müssen Sie nur die folgenden Schritte mit geänderten Paketnamen wiederholen. Ein weiteres spezielles Paket, das Sie möglicherweise installieren wollen, ist php4-pear. Dieses enthält eine minimale PEAR Installation und das Kommandozeilenprogramm pear.

Wenn Sie aktuellere Pakete als die Debian stable Pakete benötigen oder falls einige PHP Module im offiziellen Repository fehlen, sollten Sie vielleicht einen Blick auf » http://www.apt-get.org/ werfen. Eines der gefundenen Ergebnisse sollte » Dotdeb sein. Dieses inoffizielle Repository wird von » Guillaume Plessis verwaltet und enthält die aktuellsten Versionen von PHP 4 und PHP 5. Um es zu verwenden, müssen Sie nur die folgenden zwei Zeilen zu Ihrer /etc/apt/sources.list hinzufügen und apt-get update ausführen:

Beispiel #1 Die beiden Dotdeb Zeilen

deb http://packages.dotdeb.org stable all
deb-src http://packages.dotdeb.org stable all

Das Letzte, was Sie bedenken sollten ist, ob Ihre Paketliste aktuell ist. Wenn Sie diese nicht in der letzten Zeit aktualisiert haben, müssen Sie apt-get update vor allem anderen ausführen. Auf diese Weise werden Sie die aktuellsten stabilen Versionen der Apache und PHP Pakete verwenden.

Jetzt, da alles eingerichtet ist, können Sie das folgende Beispiel verwenden, um Apache und PHP zu installieren:

Beispiel #2 Debian Installationsbeispiel mit Apach 1.3.x

# apt-get install libapache-mod-php4

APT wird automatisch das PHP 4 Modul für Apache 1.3 und alle Abhängigkeiten dessen installieren und danach aktivieren. Wenn Sie nicht gefragt werden, Apache während des Installationsvorgangs neu zu starten, müssen Sie dies von Hand erledigen:

Beispiel #3 Apache anhalten und starten sobald PHP 4 installiert ist

# /etc/init.d/apache stop
# /etc/init.d/apache start

Bessere Kontrolle über die Konfiguration

Im letzten Abschnitt wurde PHP nur mit den Basismodulen installiert. Dies könnte nicht das sein, was Sie benötigen und Sie werden bald bemerken, dass Sie mehr Module wie MySQL, cURL, GD, usw benötigen.

Wenn Sie PHP selbst aus dem Quellcode kompilieren, müssen Sie die Module mit dem configure-Befehl aktivieren. Mit APT müssen Sie nur zusätzliche Pakete installieren. Diese sind alle 'php4-*' benannt (oder 'php5-*', wenn Sie PHP 5 aus einem Repository eines Drittanbieters installiert haben).

Beispiel #4 Eine Liste der zusätzlichen PHP Pakete beziehen

# dpkg -l 'php4-*'

Wie Sie aus der letzten Ausgabe entnehmen können gibt es eine ganze Reihe von PHP Modulen, die Sie installieren können (ausgenommen die php4-cgi, php4-cli oder php4-pear Spezialpakete). Sehen Sie sich diese genau an und entscheiden Sie, was Sie benötigen. Wenn Sie ein Modul auswählen und die notwendigen Bibliotheken nicht installiert sind, so wird APT automatisch alle Abhängigkeiten installieren.

Wenn Sie wählen, MySQL, cURL und GD-Unterstützung zu PHP hinzuzufügen sieht der Befehl etwa so aus:

Beispiel #5 PHP mit MySQL, cURL und GD installieren

# apt-get install php4-mysql php4-curl php4-gd

APT wird automatisch die passenden Zeilen zu Ihren verschiedenen php.ini hinzufügen (/etc/php4/apache/php.ini, /etc/php4/cgi/php.ini, usw).

Beispiel #6 Diese Zeilen aktivieren MySQL, cURL und GD in PHP

extension=mysql.so
extension=curl.so
extension=gd.so

Sie müssen nur wie vorher Apache beenden und neu starten, um die Module zu aktivieren.

Üblcihe Probleme

  • Wenn Sie den PHP Quellcode statt die Ausgabe des Skriptes sehen hat APT wahrscheinlich /etc/apache/conf.d/php4 nicht in Ihrer Apache 1.3 Konfiguration eingebunden. Stellen Sie bitte sicher, dass die folgende Zeile in Ihrer /etc/apache/httpd.conf Datei vorhanden ist und starten Sie Apache neu:

    Beispiel #7 Diese Zeile aktiviert PHP 4 in Apache

    # Include /etc/apache/conf.d/
  • Wenn Sie zusätzliche Module installiert haben und deren Funktionen nicht in Ihren Skripten zur Verfügung stehen, stellen Sie bitte sicher, dass die passende Zeile in Ihrer php.ini wie vorher gesehen vorhanden ist. APT könnte während der Installation zusätzlicher Module aufgrund einer verwirrenden debconf Konfiguration daran scheitern.



Installation unter Mac OS X

Inhaltsverzeichnis

Diese Kapitel beschreibt die Installtion von PHP im Hinblick auf Mac OS X. Es gibt zwei unterschiedliche Versionen für Mac OS X, Client und Server. Die Anleitung geht auf beide Versionen ein. PHP ist nicht verfügbar für MacOS 9 oder ältere Versionen.


Verwendung von Paketen

Es gibt verschiedene vorkompilierte und gepackte Versionen von PHP für Mac OS X. Sie können zum Aufsetzen von Standardkonfigurationen verwendet werden. Sobald Sie spezielle Funktionen benötigen (z.B. unterschiedliche Datenbanktreiber), werden Sie sich Ihr eigenes PHP - eventuell auch einen eigenen Webserver - kompilieren müssen. Wenn Sie nicht vertraut mit dem Kompilieren eigener Software sind, macht es Sinn zu prüfen, ob nicht bereits jemand ein gepacktes und vorkompiliertes System bereitstellt, dass Ihren Anforderungen entspricht.

Die folgenden Quellen bieten einfach zu installierende Pakete für PHP für Mac OS X an:



Das enthaltene PHP verwenden

Seit der Version 10.0.0 ist PHP standardmäßig in MacOS X enthalten. Um PHP mit dem Standard-Webserver zu verwenden, müssen nur ein paar Zeilen in der Apache Konfigurationsdatei httpd.conf auskommentiert werden. CGI und/oder CLI sind standardmäßig aktiviert (zugänglich über das Terminal-Programm).

Die folgende Anleitung, um PHP zu aktivieren, ermöglicht ein einfaches und schnelles Aufsetzen einer lokalen Entwicklungsumgebung. Es wird dringend empfohlen PHP immer auf dem neusten Stand zu halten. Wie für die meisten Anwendungen werden auch für PHP regelmäßig neue Version erstellt, um Fehler zu beseitigen und um den Funktionsumfang zu erweitern. Für weitere Informationen sollten Sie die entsprechende MacOS X Installations-Dokumentation lesen. Die folgende Anleitung richtet sich an Anfänger, um eine Standardkonfiguration aufzusetzen. Alle Benutzer sollten angespornt sein neuere Paket-Versionen zu installieren oder selbst zu kompilieren.

Die normale Installation beinhaltet die Aktivierung des mitgelieferten mod_php's für den Apache-Webserver (Standard-Webserver, der über die Systemeinstellungen von MacOS X zugänglich ist) und umfaßt folgende Schritte:

  1. Öffnen Sie die Apache Konfigurationsdatei. Normalerweise finden Sie diese unter: /etc/httpd/httpd.conf Über den Finder oder Spotlight wird die Datei nur schwer zu finden sein, da sie privat ist und den Rechten des root-Benutzers unterliegt.

    Hinweis: Ein Weg, um die Datei zu öffnen, ist einen Unix-basierten Texteditor im Terminal, z.B. nano, zu verwenden. Da die Datei dem Benutzer root gehört, sollten Sie den sudo-Befehl zum Öffnen (mit Root-Rechten) verwenden. Z.B. können Sie folgendes im Terminal-Programm eingeben (danach werden Sie nach dem Passwort gefragt): sudo nano /etc/httpd/httpd.conf Nennenswerte Befehle für nano: ^w (suchen), ^o (speichern), und ^x (schließen) wobei ^ für die Strg-Taste steht.

  2. Mit einem Texteditor müssen Sie nur die Zeilen, die ähnlich wie die folgenden aussehen, einkommentieren (durch entfernen von #). Die beiden Zeilen sind nicht selten von einander getrennt, daher finden Sie beide in der Datei:

    # LoadModule php4_module libexec/httpd/libphp4.so
    
    # AddModule mod_php4.c
    
    Beachten Sie die Dateipfade. Wenn Sie zukünftig PHP selbst kompilieren, sollten die beiden Dateien ersetzt oder wieder auskommentiert werden.

  3. Stellen Sie sicher, dass die gewünschten Dateiendungen durch PHP geparst werden (z.B.: .php .html und .inc)

    Durch die bereits in der Datei httpd.conf (ab MacOS Panther), enthaltenen Angaben, werden Dateien mit der Endung .php nach dem Aktivieren von PHP automatisch geparst.

    <IfModule mod_php4.c>
        # Wenn PHP aktiviert wurde, werden .php und .phps Dateien berücksichtigt.
        AddType application/x-httpd-php .php
        AddType application/x-httpd-php-source .phps
    
        # Da die meisten Benutzer index.php verwenden möchten, aktivieren
        # wir ebenso automatisch die index.php
        <IfModule mod_dir.c>
            DirectoryIndex index.html index.php
        </IfModule>
    </IfModule>
    

  4. Stellen Sie sicher, dass durch DirectoryIndex die gewünschten richtigen Index-Dateien geladen werden. Das kann ebenfalls in httpd.conf definiert werden. Normalerweise wird index.php und index.html verwendet. Standardmäßig ist index.php aktiviert, wie oben bereits gezeigt. Passen Sie es wie gewünscht an.
  5. Pfad zur php.ini setzen oder den Standard verwenden Der Standardpfad unter MacOS X ist /usr/local/php/php.ini was durch einen Aufruf von phpinfo() belegt werden sollte. Wenn keine php.ini angegeben ist, verwendet PHP die Standardwerte. Lesen Sie dazu die entsprechenden FAQs: finding php.ini.
  6. Setzen des DocumentRoot's Das ist das Wurzelverzeichnis für alle Web-Dateien. Dateien in diesem Verzeichnis werden durch den Webserver ausgeliefert. PHP-Dateien werden zuvor geparst bevor sie an einen Browser ausgeliefert werden. Der standardmäßig gesetzte Pfad ist /Library/WebServer/Documents und kann in der httpd.conf auf einen beliebigen Pfad gesetzt werden. Alternativ ist der standardmäßige Pfad zum DocumentRoot für die einzelnen Benutzer: /Users/IHR_BENUTZER_NAME/Sites
  7. Erstellen Sie eine phpinfo() Datei

    Die phpinfo()-Funktion zeigt Informationen von PHP an. Erstellen Sie eine Datei im Verzeichnis DocumentRoot mit dem folgendne Inhalt:

    <?php phpinfo(); ?>

  8. Starten Sie den Apache neu und laden Sie die eben erzeugte PHP-Datei Um neu zu starten, können Sie entweder sudo apachectl graceful im Terminal aufrufen oder die Stop/Start Option des "Personal Web Server" in den MacOS X Systemeinstellungen verwenden. Standardmäßig sollte folgende URL zum laden von lokalen Dateien im Webbrowser genügen: http://localhost/info.php Alternativ, um Dateien aus dem DocumentRoot eines lokalen Benutzers zu laden: http://localhost/~IHR_BENUTZER_NAME/info.php

Entsprechend enden CLI (oder CGI in älteren Versionen) mit php und verwenden /usr/bin/php. Öffnen Sie das Terminal, lesen Sie das Kapitel PHP auf der Kommandozeile des PHP-Handbuchs und führen Sie php -v aus, um die PHP Version des PHP Binärprogramms zu sehen. Ein Aufruf von phpinfo() enthält diese Informationen ebenfalls.



Kompilieren für OS X Server

Mac OS X Server Installation

  1. Holen Sie sich die aktuellsten Versionen von Apache und PHP.
  2. Entpacken Sie diese, und starten Sie das configure Programm für Apache.

    ./configure --exec-prefix=/usr \
    --localstatedir=/var \
    --mandir=/usr/share/man \
    --libexecdir=/System/Library/Apache/Modules \
    --iconsdir=/System/Library/Apache/Icons \
    --includedir=/System/Library/Frameworks/Apache.framework/Versions/1.3/Headers \
    --enable-shared=max \
    --enable-module=most \
    --target=apache

  3. Wenn Sie möchten, dass der Kompilierer einige Optimierungen vornimmt, können Sie z.B. die folgende Zeile hinzufügen:

    setenv OPTIM=-O2

  4. Als nächstes wechseln Sie in das PHP 4 Quellverzeichnis und konfigurieren es.

    ./configure --prefix=/usr \
        --sysconfdir=/etc \
        --localstatedir=/var \
        --mandir=/usr/share/man \
        --with-xml \
        --with-apache=/src/apache_1.3.12

    Stellen Sie sicher, dass eventuell zusätzlich benötigte Erweiterungen (MySQL, GD, usw.) an dieser Stelle hinzugefügt werden. Zum Hinzufügen des Apaches kann die Option --with-apache mit Angabe des Pfades zu den Quelldateien, z.B. /src/apache_1.3.12, verwendet werden.

  5. Geben Sie make und make install ein. Diese Aufrufe füget ein Verzeichnis src/modules/php4 in den Quelldateien des Apaches ein.
  6. Jetzt muß der Apache konfiguriert werden, um PHP 4 mit einzubinden.

    ./configure --exec-prefix=/usr \
    --localstatedir=/var \
    --mandir=/usr/share/man \
    --libexecdir=/System/Library/Apache/Modules \
    --iconsdir=/System/Library/Apache/Icons \
    --includedir=/System/Library/Frameworks/Apache.framework/Versions/1.3/Headers \
    --enable-shared=max \
    --enable-module=most \
    --target=apache \
    --activate-module=src/modules/php4/libphp4.a

    Es kann sein, dass Sie eine Meldung erhalten, dass libmodphp4.a veraltet ist. In diesem Fall sollten sie im Apache Quellverzeichnis in das Verzeichnis src/modules/php4 wechseln und den folgenden Befehl aufrufen: ranlib libmodphp4.a. Danach gehen Sie zurück ins Wurzelverzeichnis des Apache Quellverzeichnisses und starten erneut den configure Aufruf, dass wird die Verlinkungstabelle auf den neusten Stand bringen. Rufen Sie jetzt make und make install erneut auf.

  7. Kopieren sie die Datei php.ini-dist aus Ihrem PHP 4 Quellverzeichnis unter bin und benennen Sie diese um: cp php.ini-dist /usr/local/bin/php.ini oder (wenn Sie kein local-Verzeichnis haben) cp php.ini-dist /usr/bin/php.ini .



Kompilieren unter MacOS X Client

Die folgende Anleitung erklärt, wie ein PHP Modul im Apache Webserver - bereits in Mac OS X enthalten - installiert werden kann. Das Modul beinhaltet bereits Unterstützung für die Datenbanksysteme MySQL und PostgreSQL. Diese Anleitung wurde bereitgestellt von » Marc Liyanage.

Warnung

Seien Sie vorsichtig während der Installation. Sie könnten dadurch den Apache Webserver zerstören.

Installieren Sie wie folgt:

  1. Öffnen Sie ein Terminal-Fenster.
  2. Tippen Sie wget http://www.diax.ch/users/liyanage/software/macosx/libphp4.so.gz , und warten Sie, bis der Download beendet ist.
  3. Tippen Sie gunzip libphp4.so.gz .
  4. Tippen Sie sudo apxs -i -a -n php4 libphp4.so
  5. Jetzt tippen Sie sudo open -a TextEdit /etc/httpd/httpd.conf . TextEdit wird sich öffnen und die Konfigurationsdatei des Webservers anzeigen. Suchen Sie nach den folgenden zwei Zeilen gegen Ende der Datei: (Benutzen Sie die Suchen-Funktion)

    #AddType application/x-httpd-php .php 
    #AddType application/x-httpd-php-source .phps

    Entfernen sie das Doppelkreuz (#) und speichern Sie die Datei. Sie können TextEdit wieder schließen.

  6. Zuletzt tippen Sie sudo apachectl graceful um den Webserver neu zu starten.

PHP sollte nun zur Verfügung stehen. Sie können es testen indem Sie eine Datei test.php mit dem Inhalt <?php phpinfo() ?> in Ihrem Home-Verzeichnis in den Ordner Sites legen und die URL 127.0.0.1/~your_username/test.php in Ihrem Webbrowser eingeben. Sie sollten nun eine Informationsübersicht des PHP-Moduls sehen.




Installation on Windows systems

Inhaltsverzeichnis

This section applies to Windows 98/Me and Windows NT/2000/XP/2003. PHP will not work on 16 bit platforms such as Windows 3.1 and sometimes we refer to the supported Windows platforms as Win32. Windows 95 is no longer supported as of PHP 4.3.0.

Hinweis: Windows 98/ME/NT4 is no longer supported as of PHP 5.3.0.

Hinweis: Windows 95 is no longer supported as of PHP 4.3.0.

There are two main ways to install PHP for Windows: either manually or by using the installer.

If you have Microsoft Visual Studio, you can also build PHP from the original source code.

Once you have PHP installed on your Windows system, you may also want to load various extensions for added functionality.

Warnung

There are several all-in-one installers over the Internet, but none of those are endorsed by PHP.net, as we believe that using one of the official windows packages from » http://www.php.net/downloads.php is the best choice to have your system secure and optimized.


Windows Installer (PHP 5.1.0 and earlier)

The Windows PHP installer is available from the downloads page at » http://www.php.net/downloads.php. This installs the CGI version of PHP and for IIS, PWS, and Xitami, it configures the web server as well. The installer does not include any extra external PHP extensions (php_*.dll) as you'll only find those in the Windows Zip Package and PECL downloads.

Hinweis: While the Windows installer is an easy way to make PHP work, it is restricted in many aspects as, for example, the automatic setup of extensions is not supported. Use of the installer isn't the preferred method for installing PHP.

First, install your selected HTTP (web) server on your system, and make sure that it works.

Run the executable installer and follow the instructions provided by the installation wizard. Two types of installation are supported - standard, which provides sensible defaults for all the settings it can, and advanced, which asks questions as it goes along.

The installation wizard gathers enough information to set up the php.ini file, and configure certain web servers to use PHP. One of the web servers the PHP installer does not configure for is Apache, so you'll need to configure it manually.

Once the installation has completed, the installer will inform you if you need to restart your system, restart the server, or just start using PHP.

Warnung

Be aware, that this setup of PHP is not secure. If you would like to have a secure PHP setup, you'd better go on the manual way, and set every option carefully. This automatically working setup gives you an instantly working PHP installation, but it is not meant to be used on online servers.



Windows Installer (PHP 5.2 and later)

The Windows PHP installer for later versions of PHP is built using MSI technology using the Wix Toolkit (» http://wix.sourceforge.net/). It will install and configure PHP and all the built-in and PECL extensions, as well as configure many of the popular web servers such as IIS, Apache, and Xitami.

First, install your selected HTTP (web) server on your system, and make sure that it works. Then proceed with one of the following install types.

Normal Install

Run the MSI installer and follow the instructions provided by the installation wizard. You will be prompted to select the Web Server you wish to configure first, along with any configuration details needed.

You will then be prompted to select which features and extensions you wish to install and enable. By selecting "Will be installed on local hard drive" in the drop-down menu for each item you can trigger whether to install the feature or not. By selecting "Entire feature will be installed on local hard drive", you will be able to install all sub-features of the included feature ( for example by selecting this options for the feature "PDO" you will install all PDO Drivers ).

Warnung

It is not recommended to install all extensions by default, since many other them require dependencies from outside PHP in order to function properly. Instead, use the Installation Repair Mode that can be triggered thru the 'Add/Remove Programs' control panel to enable or disable extensions and features after installation.

The installer then sets up PHP to be used in Windows and the php.ini file, and configures certain web servers to use PHP. The installer will currently configure IIS, Apache, Xitami, and Sambar Server; if you are using a different web server you'll need to configure it manually.

Silent Install

The installer also supports a silent mode, which is helpful for Systems Administrators to deploy PHP easily. To use silent mode:

       
msiexec.exe /i php-VERSION-win32-install.msi /q

You can control the install directory by passing it as a parameter to the install. For example, to install to e:\php:

       
msiexec.exe /i php-VERSION-win32-install.msi /q INSTALLDIR=e:\php
You can also use the same syntax to specify the Apache Configuration Directory (APACHEDIR), the Sambar Server directory (SAMBARDIR), and the Xitami Server directory (XITAMIDIR).

You can also specify what features to install. For example, to install the mysqli extension and the CGI executable:

       
msiexec.exe /i php-VERSION-win32-install.msi /q ADDLOCAL=cgi,ext_php_mysqli

The current list of Features to install is as follows:

 
MainExecutable - php.exe executable ( no longer available as of PHP 5.2.10/5.3.0; it is now included by default )
ScriptExecutable - php-win.exe executable
ext_php_* - the various extensions ( for example: ext_php_mysql for MySQL )
apache13 - Apache 1.3 module
apache20 - Apache 2.0 module
apache22 - Apache 2,2 module
apacheCGI - Apache CGI executable
iis4ISAPI - IIS ISAPI module
iis4CGI - IIS CGI executable
iis4FastCGI - IIS CGI executable
NSAPI - Sun/iPlanet/Netscape server module
netserve - NetServe Web Server CGI executable
Xitami - Xitami CGI executable
Sambar - Sambar Server ISAPI module
CGI - php-cgi.exe executable
PEAR - PEAR installer
Manual - PHP Manual in CHM Format

For more information on installing MSI installers from the command line, visit » http://msdn.microsoft.com/en-us/library/aa367988.aspx

Upgrading PHP with the Install

To upgrade, run the installer either graphically or from the command line as normal. The installer will read your current install options, remove your old installation, and reinstall PHP with the same options as before. It is recommended that you use this method of keeping PHP updated instead of manually replacing the files in the installation directory.



Manual Installation Steps

This section contains instructions for manually installing and configuring PHP on Microsoft Windows. For the instructions on how to use PHP installer to setup and configure PHP and a web server on Windows refer to Windows Installer (PHP 5.2 and later).

Selecting and downloading the PHP distribution package

Download the PHP zip binary distribution from » PHP for Windows: Binaries and Sources. There are several different versions of the zip package - chose the version that is suitable for the web server being used:

  • If PHP is used with IIS then choose PHP 5.3 VC9 Non Thread Safe or PHP 5.2 VC6 Non Thread Safe;

  • If PHP is used with Apache 1 or Apache 2 then choose PHP 5.3 VC6 or PHP 5.2 VC6.

Hinweis: VC9 Versions are compiled with the Visual Studio 2008 compiler and have improvements in performance and stability. The VC9 versions require you to have the » Microsoft 2008 C++ Runtime (x86) or the » Microsoft 2008 C++ Runtime (x64) installed.

The PHP package structure and content

Unpack the content of the zip archive into a directory of your choice, for example C:\PHP\. The directory and file structure extracted from the zip will look as below:

Beispiel #1 PHP 5 package structure


c:\php
   |
   +--dev
   |  |
   |  |-php5ts.lib                 -- php5.lib in non thread safe version
   |
   +--ext                          -- extension DLLs for PHP
   |  |
   |  |-php_bz2.dll
   |  |
   |  |-php_cpdf.dll
   |  |
   |  |-...
   |
   +--extras                       -- empty 
   |
   +--pear                         -- initial copy of PEAR
   |
   |
   |-go-pear.bat                   -- PEAR setup script
   |
   |-...
   |
   |-php-cgi.exe                   -- CGI executable
   |
   |-php-win.exe                   -- executes scripts without an opened command prompt
   |
   |-php.exe                       -- Command line PHP executable (CLI)
   |
   |-...
   |
   |-php.ini-development           -- default php.ini settings
   |
   |-php.ini-production            -- recommended php.ini settings
   |
   |-php5apache2_2.dll             -- does not exist in non thread safe version
   |
   |-php5apache2_2_filter.dll      -- does not exist in non thread safe version
   |
   |-...
   |
   |-php5ts.dll                    -- core PHP DLL ( php5.dll in non thread safe version)
   | 
   |-...

Below is the list of the modules and executables included in the PHP zip distribution:

  • go-pear.bat - the PEAR setup script. Refer to » Installation (PEAR) for more details.

  • php-cgi.exe - CGI executable that can be used when running PHP on IIS via CGI or FastCGI.

  • php-win.exe - the PHP executable for executing PHP scripts without using a command line window (for example PHP applications that use Windows GUI).

  • php.exe - the PHP executable for executing PHP scripts within a command line interface (CLI).

  • php5apache2_2.dll - Apache 2.2.X module.

  • php5apache2_2_filter.dll - Apache 2.2.X filter.

Changing the php.ini file

After the php package content has been extracted, copy the php.ini-production into php.ini in the same folder. If necessary, it is also possible to place the php.ini into any other location of your choice but that will require additional configuration steps as described in PHP Configuration.

The php.ini file tells PHP how to configure itself, and how to work with the environment that it runs in. Here are a number of settings for the php.ini file that help PHP work better with Windows. Some of these are optional. There are many other directives that may be relevant to your environment - refer to the list of php.ini directives for more information.

Required directives:

  • extension_dir = <path to extension directory> - The extension_dir needs to point to the directory where PHP extensions files are stored. The path can be absolute (i.e. "C:\PHP\ext") or relative (i.e. ".\ext"). Extensions that are listed lower in the php.ini file need to be located in the extension_dir.

  • extension = xxxxx.dll - For each extension you wish to enable, you need a corresponding "extension=" directive that tells PHP which extensions in the extension_dir to load at startup time.

  • log_errors = On - PHP has an error logging facility that can be used to send errors to a file, or to a service (i.e. syslog) and works in conjunction with the error_log directive below. When running under IIS, the log_errors should be enabled, with a valid error_log.

  • error_log = <path to the error log file> - The error_log needs to specify the absolute, or relative path to the file where PHP errors should be logged. This file needs to be writable for the web server. The most common places for this file are in various TEMP directories, for example "C:\inetpub\temp\php-errors.log".

  • cgi.force_redirect = 0 - This directive is required for running under IIS. It is a directory security facility required by many other web servers. However, enabling it under IIS will cause the PHP engine to fail on Windows.

  • cgi.fix_pathinfo = 1 - This lets PHP access real path info following the CGI Spec. The IIS FastCGI implementation needs this set.

  • fastcgi.impersonate = 1 - FastCGI under IIS supports the ability to impersonate security tokens of the calling client. This allows IIS to define the security context that the request runs under.

  • fastcgi.logging = 0 - FastCGI logging should be disabled on IIS. If it is left enabled, then any messages of any class are treated by FastCGI as error conditions which will cause IIS to generate an HTTP 500 exception.

Optional directives

  • max_execution_time = ## - This directive tells PHP the maximum amount of time that it can spend executing any given script. The default for this is 30 seconds. Increase the value of this directive if PHP application take long time to execute.

  • memory_limit = ###M - The amount of memory available for the PHP process, in Megabytes. The default is 128, which is fine for most PHP applications. Some of the more complex ones might need more.

  • display_errors = Off - This directive tells PHP whether to include any error messages in the stream that it returns to the Web server. If this is set to "On", then PHP will send whichever classes of errors that you define with the error_reporting directive back to web server as part of the error stream. For security reasons it is recommended to set it to "Off" on production servers in order not to reveal any security sensitive information that is often included in the error messages.

  • open_basedir = <paths to directories, separated by semicolon>, e.g. openbasedir="C:\inetpub\wwwroot;C:\inetpub\temp". This directive specified the directory paths where PHP is allowed to perform file system operations. Any file operation outside of the specified paths will result in an error. This directive is especially useful for locking down the PHP installation in shared hosting environments to prevent PHP scripts from accessing any files outside of the web site's root directory.

  • upload_max_filesize = ###M and post_max_size = ###M - The maximum allowed size of an uploaded file and post data respectively. The values of these directives should be increased if PHP applications need to perform large uploads, such as for example photos or video files.

PHP is now setup on your system. The next step is to choose a web server, and enable it to run PHP. Choose a web server from the table of contents.

In addition to running PHP via a web server, PHP can run from the command line just like a .BAT script. See Command Line PHP on Microsoft Windows for further details.



ActiveScript

This section contains notes specific to the ActiveScript installation.

ActiveScript is a Windows only SAPI that enables you to use PHP script in any ActiveScript compliant host, like Windows Script Host, ASP/ASP.NET, Windows Script Components or Microsoft Scriptlet control.

As of PHP 5.0.1, ActiveScript has been moved to the » PECL repository. Sie können die DLL für diese PECL-Extension entweder von » PHP-Downloads oder von » http://pecl4win.php.net/ herunterladen.

Hinweis: You should read the manual installation steps first!

After installing PHP, you should download the ActiveScript DLL (php5activescript.dll) and place it in the main PHP folder (e.g. C:\php).

After having all the files needed, you must register the DLL on your system. To achieve this, open a Command Prompt window (located in the Start Menu). Then go to your PHP directory by typing something like cd C:\php. To register the DLL just type regsvr32 php5activescript.dll.

To test if ActiveScript is working, create a new file, named test.wsf (the extension is very important) and type:

<job id="test">
 
 <script language="PHPScript">
  $WScript->Echo("Hello World!");
 </script>
 
</job>

Save and double-click on the file. If you receive a little window saying "Hello World!" you're done.

Hinweis: In PHP 4, the engine was named 'ActivePHP', so if you are using PHP 4, you should replace 'PHPScript' with 'ActivePHP' in the above example.

Hinweis: ActiveScript doesn't use the default php.ini file. Instead, it will look only in the same directory as the .exe that caused it to load. You should create php-activescript.ini and place it in that folder, if you wish to load extensions, etc.



Microsoft IIS

This section contains PHP installation instructions specific to Microsoft Internet Information Services (IIS).



Microsoft IIS 5.1 and IIS 6.0

This section contains instructions for manually setting up Internet Information Services (IIS) 5.1 and IIS 6.0 to work with PHP on Microsoft Windows XP and Windows Server 2003. For instructions on setting up IIS 7.0 and later versions on Windows Vista, Windows Server 2008, Windows 7 and Windows Server 2008 R2 refer to Microsoft IIS 7.0 and later.

Configuring IIS to process PHP requests

Download and install PHP in accordance to the instructions described in manual installation steps

Hinweis: Non-thread-safe build of PHP is recommended when using IIS. The non-thread-safe builds are available at » PHP for Windows: Binaries and Sources Releases.

Configure the CGI- and FastCGI-specific settings in php.ini file as shown below:

Beispiel #1 CGI and FastCGI settings in php.ini

fastcgi.impersonate = 1
fastcgi.logging = 0
cgi.fix_pathinfo=1
cgi.force_redirect = 0

Download and install the » Microsoft FastCGI Extension for IIS 5.1 and 6.0. The extension is available for 32-bit and 64-bit platforms - select the right download package for your platform.

Configure the FastCGI extension to handle PHP-specific requests by running the command shown below. Replace the value of the "-path" parameter with the absolute file path to the php-cgi.exe file.

Beispiel #2 Configuring FastCGI extension to handle PHP requests

cscript %windir%\system32\inetsrv\fcgiconfig.js -add -section:"PHP" ^
-extension:php -path:"C:\PHP\php-cgi.exe"

This command will create an IIS script mapping for *.php file extension, which will result in all URLs that end with .php being handled by FastCGI extension. Also, it will configure FastCGI extension to use the executable php-cgi.exe to process the PHP requests.

Hinweis: At this point the required installation and configuration steps are completed. The remaining instructions below are optional but highly recommended for achieving optimal functionality and performance of PHP on IIS.

Impersonation and file system access

It is recommended to enable FastCGI impersonation in PHP when using IIS. This is controlled by the fastcgi.impersonate directive in php.ini file. When impersonation is enabled, PHP will perform all the file system operations on behalf of the user account that has been determined by IIS authentication. This ensures that even if the same PHP process is shared across different IIS web sites, the PHP scripts in those web sites will not be able to access each others' files as long as different user accounts are used for IIS authentication on each web site.

For example IIS 5.1 and IIS 6.0, in its default configuration, has anonymous authentication enabled with built-in user account IUSR_<MACHINE_NAME> used as a default identity. This means that in order for IIS to execute PHP scripts, it is necessary to grant IUSR_<MACHINE_NAME> account read permission on those scripts. If PHP applications need to perform write operations on certain files or write files into some folders then IUSR_<MACHINE_NAME> account should have write permission to those.

To determine which user account is used by IIS anonymous authentication, follow these steps:

  1. In the Windows Start Menu choose "Run:", type "inetmgr" and click "Ok";

  2. Expand the list of web sites under the "Web Sites" node in the tree view, right-click on a web site that is being used and select "Properties";

  3. Click the "Directory Security" tab;

  4. Take note of a "User name:" field in the "Authentication Methods" dialog

To modify the permissions settings on files and folders, use the Windows Explorer user interface or icacls command.

Beispiel #3 Configuring file access permissions

icacls C:\inetpub\wwwroot\upload /grant IUSR:(OI)(CI)(M)

Set index.php as a default document in IIS

The IIS default documents are used for HTTP requests that do not specify a document name. With PHP applications, index.php usually acts as a default document. To add index.php to the list of IIS default documents, follow these steps:

  1. In the Windows Start Menu choose "Run:", type "inetmgr" and click "Ok";

  2. Right-click on the "Web Sites" node in the tree view and select "Properties";

  3. Click the "Documents" tab;

  4. Click the "Add..." button and enter "index.php" for the "Default content page:".

FastCGI and PHP Recycling configuration

Configure IIS FastCGI extension settings for recycling of PHP processes by using the commands shown below. The FastCGI setting instanceMaxRequests controls how many requests will be processed by a single php-cgi.exe process before FastCGI extension shuts it down. The PHP environment variable PHP_FCGI_MAX_REQUESTS controls how many requests a single php-cgi.exe process will handle before it recycles itself. Make sure that the value specified for FastCGI InstanceMaxRequests setting is less than or equal to the value specified for PHP_FCGI_MAX_REQUESTS.

Beispiel #4 Configuring FastCGI and PHP recycling

cscript %windir%\system32\inetsrv\fcgiconfig.js -set -section:"PHP" ^
-InstanceMaxRequests:10000

cscript %windir%\system32\inetsrv\fcgiconfig.js -set -section:"PHP" ^
-EnvironmentVars:PHP_FCGI_MAX_REQUESTS:10000

Configuring FastCGI timeout settings

Increase the timeout settings for FastCGI extension if there are applications that have long running PHP scripts. The two settings that control timeouts are ActivityTimeout and RequestTimeout. Refer to » Configuring FastCGI Extension for IIS 6.0 for more information about those settings.

Beispiel #5 Configuring FastCGI timeout settings

cscript %windir%\system32\inetsrv\fcgiconfig.js -set -section:"PHP" ^
-ActivityTimeout:90

cscript %windir%\system32\inetsrv\fcgiconfig.js -set -section:"PHP" ^
-RequestTimeout:90

Changing the Location of php.ini file

PHP searches for php.ini file in several locations and it is possible to change the default locations of php.ini file by using PHPRC environment variable. To instruct PHP to load the configuration file from a custom location run the command shown below. The absolute path to the directory with php.ini file should be specified as a value of PHPRC environment variable.

Beispiel #6 Changing the location of php.ini file

cscript %windir%\system32\inetsrv\fcgiconfig.js -set -section:"PHP" ^
-EnvironmentVars:PHPRC:"C:\Some\Directory\"



Microsoft IIS 7.0 and later

This section contains instructions for manually setting up Internet Information Services (IIS) 7.0 and later to work with PHP on Microsoft Windows Vista SP1, Windows 7, Windows Server 2008 and Windows Server 2008 R2. For instructions on setting up IIS 5.1 and IIS 6.0 on Windows XP and Windows Server 2003 refer to Microsoft IIS 5.1 and IIS 6.0.

Enabling FastCGI support in IIS

FastCGI module is disabled in default installation of IIS. The steps to enable it differ based on the version of Windows being used.

To enable FastCGI support on Windows Vista SP1 and Windows 7:

  1. In the Windows Start Menu choose "Run:", type "optionalfeatures.exe" and click "Ok";

  2. In the "Windows Features" dialog expand "Internet Information Services", "World Wide Web Services", "Application Development Features" and then enable the "CGI" checkbox;

  3. Click OK and wait until the installation is complete.

To enable FastCGI support on Windows Server 2008 and Windows Server 2008 R2:

  1. In the Windows Start Menu choose "Run:", type "CompMgmtLauncher" and click "Ok";

  2. If the "Web Server (IIS)" role is not present under the "Roles" node, then add it by clicking "Add Roles";

  3. If the "Web Server (IIS)" role is present, then click "Add Role Services" and then enable the "CGI" checkbox under "Application Development" group;

  4. Click "Next" and then "Install" and wait for the installation to complete.

Configuring IIS to process PHP requests

Download and install PHP in accordance to the instructions described in manual installation steps

Hinweis: Non-thread-safe build of PHP is recommended when using IIS. The non-thread-safe builds are available at » PHP for Windows: Binaries and Sources Releases.

Configure the CGI- and FastCGI-specific settings in php.ini file as shown below:

Beispiel #1 CGI and FastCGI settings in php.ini

fastcgi.impersonate = 1
fastcgi.logging = 0
cgi.fix_pathinfo=1
cgi.force_redirect = 0

Configure IIS handler mapping for PHP by using either IIS Manager user interface or a command line tool.

Using IIS Manager user interface to create a handler mapping for PHP

Follow these steps to create an IIS handler mapping for PHP in IIS Manager user interface:

  1. In the Windows Start Menu choose "Run:", type "inetmgr" and click "Ok";

  2. In the IIS Manager user interface select the server node in the "Connections" tree view;

  3. In the "Features View" page open the "Handler Mappings" feature;

  4. In the "Actions" pane click "Add Module Mapping...";

  5. In the "Add Module Mapping" dialog enter the following:

    • Request path: *.php
    • Module: FastCgiModule
    • Executable: C:\[Path to PHP installation]\php-cgi.exe
    • Name: PHP_via_FastCGI

  6. Click "Request Restrictions" button and then configure the mapping to invoke handler only if request is mapped to a file or a folder;

  7. Click OK on all the dialogs to save the configuration.

Using command line tool to create a handler mapping for PHP

Use the command shown below to create an IIS FastCGI process pool which will use php-cgi.exe executable for processing PHP requests. Replace the value of the fullPath parameter with the absolute file path to the php-cgi.exe file.

Beispiel #2 Creating IIS FastCGI process pool

%windir%\system32\inetsrv\appcmd set config /section:system.webServer/fastCGI ^
/+[fullPath='c:\PHP\php-cgi.exe']

Configure IIS to handle PHP specific requests by running the command shown below. Replace the value of the scriptProcessor parameter with the absolute file path to the php-cgi.exe file.

Beispiel #3 Creating handler mapping for PHP requests

%windir%\system32\inetsrv\appcmd set config /section:system.webServer/handlers ^
/+[name='PHP_via_FastCGI', path='*.php',verb='*',modules='FastCgiModule',^
scriptProcessor='c:\PHP\php-cgi.exe',resourceType='Either']

This command creates an IIS handler mapping for *.php file extension, which will result in all URLs that end with .php being handled by FastCGI module.

Hinweis: At this point the required installation and configuration steps are completed. The remaining instructions below are optional but highly recommended for achieving optimal functionality and performance of PHP on IIS.

Impersonation and file system access

It is recommended to enable FastCGI impersonation in PHP when using IIS. This is controlled by the fastcgi.impersonate directive in php.ini file. When impersonation is enabled, PHP will perform all the file system operations on behalf of the user account that has been determined by IIS authentication. This ensures that even if the same PHP process is shared across different IIS web sites, the PHP scripts in those web sites will not be able to access each other's files as long as different user accounts are used for IIS authentication on each web site.

For example IIS 7, in its default configuration, has anonymous authentication enabled with built-in user account IUSR used as a default identity. This means that in order for IIS to execute PHP scripts, it is necessary to grant IUSR account read permission on those scripts. If PHP applications need to perform write operations on certain files or write files into some folders then IUSR account should have write permission to those.

To determine what user account is used as an anonymous identity in IIS 7 use the following command. Replace the "Default Web Site" with the name of IIS web site that you use. In the output XML configuration element look for the userName attribute.

Beispiel #4 Determining the account used as IIS anonymous identity

%windir%\system32\inetsrv\appcmd.exe list config "Default Web Site" ^
/section:anonymousAuthentication

<system.webServer>
  <security>
    <authentication>
      <anonymousAuthentication enabled="true" userName="IUSR" />
    </authentication>
   </security>
</system.webServer>

Hinweis: If userName attribute is not present in the anonymousAuthentication element, or is set to an empty string, then it means that the application pool identity is used as an anonymous identity for that web site.

To modify the permissions settings on files and folders, use the Windows Explorer user interface or icacls command.

Beispiel #5 Configuring file access permissions

icacls C:\inetpub\wwwroot\upload /grant IUSR:(OI)(CI)(M)

Set index.php as a default document in IIS

The IIS default documents are used for HTTP requests that do not specify a document name. With PHP applications, index.php usually acts as a default document. To add index.php to the list of IIS default documents, use this command:

Beispiel #6 Set index.php as a default document in IIS

%windir%\system32\inetsrv\appcmd.exe set config ^
-section:system.webServer/defaultDocument /+"files.[value='index.php']" ^
/commit:apphost

FastCGI and PHP Recycling configuration

Configure IIS FastCGI settings for recycling of PHP processes by using the commands shown below. The FastCGI setting instanceMaxRequests controls how many requests will be processed by a single php-cgi.exe process before IIS shuts it down. The PHP environment variable PHP_FCGI_MAX_REQUESTS controls how many requests a single php-cgi.exe process will handle before it recycles itself. Make sure that the value specified for FastCGI InstanceMaxRequests setting is less than or equal to the value specified for PHP_FCGI_MAX_REQUESTS.

Beispiel #7 Configuring FastCGI and PHP recycling

%windir%\system32\inetsrv\appcmd.exe set config -section:system.webServer/fastCgi ^
/[fullPath='c:\php\php-cgi.exe'].instanceMaxRequests:10000

%windir%\system32\inetsrv\appcmd.exe set config -section:system.webServer/fastCgi ^
/+"[fullPath='C:\{php_folder}\php-cgi.exe'].environmentVariables.^
[name='PHP_FCGI_MAX_REQUESTS',value='10000']"

Configuring FastCGI timeout settings

Increase the timeout settings for FastCGI if it is expected to have long running PHP scripts. The two settings that control timeouts are activityTimeout and requestTimeout. Use the commands below to change the timeout settings. Make sure to replace the value in the fullPath parameter to contain the absolute path to the php-cgi.exe file.

Beispiel #8 Configuring FastCGI and PHP recycling

%windir%\system32\inetsrv\appcmd.exe set config -section:system.webServer/fastCgi ^
/[fullPath='C:\php\php-cgi.exe',arguments=''].activityTimeout:"90"  /commit:apphost

%windir%\system32\inetsrv\appcmd.exe set config -section:system.webServer/fastCgi ^
/[fullPath='C:\php\php-cgi.exe',arguments=''].requestTimeout:"90"  /commit:apphost

Changing the Location of php.ini file

PHP searches for php.ini file in several locations and it is possible to change the default locations of php.ini file by using PHPRC environment variable. To instruct PHP to load the configuration file from a custom location run the command shown below. The absolute path to the directory with php.ini file should be specified as a value of PHPRC environment variable.

Beispiel #9 Changing the location of php.ini file

appcmd.exe set config  -section:system.webServer/fastCgi ^
/+"[fullPath='C:\php\php.exe',arguments=''].environmentVariables.^
[name='PHPRC',value='C:\Some\Directory\']" /commit:apphost



Apache 1.3.x on Microsoft Windows

This section contains notes and hints specific to Apache 1.3.x installs of PHP on Microsoft Windows systems. There are also instructions and notes for Apache 2 on a separate page.

Hinweis: Please read the manual installation steps first!

There are two ways to set up PHP to work with Apache 1.3.x on Windows. One is to use the CGI binary (php.exe for PHP 4 and php-cgi.exe for PHP 5), the other is to use the Apache Module DLL. In either case you need to edit your httpd.conf to configure Apache to work with PHP, and then restart the server.

It is worth noting here that now the SAPI module has been made more stable under Windows, we recommend it's use above the CGI binary, since it is more transparent and secure.

Although there can be a few variations of configuring PHP under Apache, these are simple enough to be used by the newcomer. Please consult the Apache Documentation for further configuration directives.

After changing the configuration file, remember to restart the server, for example, NET STOP APACHE followed by NET START APACHE, if you run Apache as a Windows Service, or use your regular shortcuts.

Hinweis: Beachten Sie bitte, dass Sie bei Pfadangaben in der Apachekonfigurationsdatei unter Windows alle Backslashes, wie z.B. c:\directory\file.ext, in Schrägstriche umwandeln müssen: c:/directory/file.ext. Bei Verzeichnisnamen kann weiterhin ein abschließender Schrägstrich nötig sein.

Installing as an Apache module

You should add the following lines to your Apache httpd.conf file:

Beispiel #1 PHP as an Apache 1.3.x module

This assumes PHP is installed to c:\php. Adjust the path if this is not the case.

For PHP 4:

# Add to the end of the LoadModule section
# Don't forget to copy this file from the sapi directory!
LoadModule php4_module "C:/php/php4apache.dll"

# Add to the end of the AddModule section
AddModule mod_php4.c

For PHP 5:

# Add to the end of the LoadModule section
LoadModule php5_module "C:/php/php5apache.dll"

# Add to the end of the AddModule section
AddModule mod_php5.c

For both:

# Add this line inside the <IfModule mod_mime.c> conditional brace
AddType application/x-httpd-php .php

# For syntax highlighted .phps files, also add
AddType application/x-httpd-php-source .phps

Installing as a CGI binary

If you unzipped the PHP package to C:\php\ as described in the Manual Installation Steps section, you need to insert these lines to your Apache configuration file to set up the CGI binary:

Beispiel #2 PHP and Apache 1.3.x as CGI

ScriptAlias /php/ "c:/php/"
AddType application/x-httpd-php .php

# For PHP 4
Action application/x-httpd-php "/php/php.exe"

# For PHP 5
Action application/x-httpd-php "/php/php-cgi.exe"

# specify the directory where php.ini is
SetEnv PHPRC C:/php

Note that the second line in the list above can be found in the actual versions of httpd.conf, but it is commented out. Remember also to substitute the c:/php/ for your actual path to PHP.

Warnung

Wenn Sie das CGI-Setup verwenden, ist Ihr Server für einige mögliche Angriffe anfällig. Wie Sie sich vor diesen Angriffen schützen können, entnehmen Sie bitte dem Kapitel über CGI-Sicherheit.

If you would like to present PHP source files syntax highlighted, there is no such convenient option as with the module version of PHP. If you chose to configure Apache to use PHP as a CGI binary, you will need to use the highlight_file() function. To do this simply create a PHP script file and add this code: <?php highlight_file('some_php_script.php'); ?>.



Apache 2.0.x on Microsoft Windows

This section contains notes and hints specific to Apache 2.0.x installs of PHP on Microsoft Windows systems. We also have instructions and notes for Apache 1.3.x users on a separate page.

Hinweis: You should read the manual installation steps first!

Hinweis: Apache 2.2.x Support
Users of Apache 2.2.x may use the documentation below except the appropriate DLL file is named php5apache2_2.dll and it only exists as of PHP 5.2.0. See also » http://snaps.php.net/

Warnung

Wir empfehlen, in einer Produktionsumgebung kein Threaded MPM mit Apache2 zu verwenden. Verwenden Sie stattdessen das Prefork MPM oder Apache1. Für weitere Informationen und die Gründe lesen Sie bitte den entsprechenden FAQ-Eintrag über die Verwendung von Apache2 mit Threaded MPM.

You are highly encouraged to take a look at the » Apache Documentation to get a basic understanding of the Apache 2.0.x Server. Also consider to read the » Windows specific notes for Apache 2.0.x before reading on here.

Hinweis: PHP and Apache 2.0.x compatibility notes
The following versions of PHP are known to work with the most recent version of Apache 2.0.x:

These versions of PHP are compatible to Apache 2.0.40 and later.
Apache 2.0 SAPI-support started with PHP 4.2.0. PHP 4.2.3 works with Apache 2.0.39, don't use any other version of Apache with PHP 4.2.3. However, the recommended setup is to use PHP 4.3.0 or later with the most recent version of Apache2.
All mentioned versions of PHP will work still with Apache 1.3.x.

Warnung

Apache 2.0.x is designed to run on Windows NT 4.0, Windows 2000 or Windows XP. At this time, support for Windows 9x is incomplete. Apache 2.0.x is not expected to work on those platforms at this time.

Download the most recent version of » Apache 2.0.x and a fitting PHP version. Follow the Manual Installation Steps and come back to go on with the integration of PHP and Apache.

There are two ways to set up PHP to work with Apache 2.0.x on Windows. One is to use the CGI binary the other is to use the Apache module DLL. In either case you need to edit your httpd.conf to configure Apache to work with PHP and then restart the server.

Hinweis: Beachten Sie bitte, dass Sie bei Pfadangaben in der Apachekonfigurationsdatei unter Windows alle Backslashes, wie z.B. c:\directory\file.ext, in Schrägstriche umwandeln müssen: c:/directory/file.ext. Bei Verzeichnisnamen kann weiterhin ein abschließender Schrägstrich nötig sein.

Installing as a CGI binary

You need to insert these three lines to your Apache httpd.conf configuration file to set up the CGI binary:

Beispiel #1 PHP and Apache 2.0 as CGI

ScriptAlias /php/ "c:/php/"
AddType application/x-httpd-php .php

# For PHP 4
Action application/x-httpd-php "/php/php.exe"

# For PHP 5
Action application/x-httpd-php "/php/php-cgi.exe"

Warnung

Wenn Sie das CGI-Setup verwenden, ist Ihr Server für einige mögliche Angriffe anfällig. Wie Sie sich vor diesen Angriffen schützen können, entnehmen Sie bitte dem Kapitel über CGI-Sicherheit.

Installing as an Apache module

You need to insert these two lines to your Apache httpd.conf configuration file to set up the PHP module for Apache 2.0:

Beispiel #2 PHP and Apache 2.0 as Module

# For PHP 4 do something like this:
LoadModule php4_module "c:/php/php4apache2.dll"
# Don't forget to copy the php4apache2.dll file from the sapi directory!
AddType application/x-httpd-php .php

# For PHP 5 do something like this:
LoadModule php5_module "c:/php/php5apache2.dll"
AddType application/x-httpd-php .php

# configure the path to php.ini
PHPIniDir "C:/php"

Hinweis: Remember to substitute your actual path to PHP for the c:/php/ in the above examples. Take care to use either php4apache2.dll or php5apache2.dll in your LoadModule directive and not php4apache.dll or php5apache.dll as the latter ones are designed to run with Apache 1.3.x.

Hinweis: If you want to use content negotiation, read related FAQ.

Warnung

Don't mix up your installation with DLL files from different PHP versions. You have the only choice to use the DLL's and extensions that ship with your downloaded PHP version.



Sun, iPlanet and Netscape servers on Microsoft Windows

This section contains notes and hints specific to Sun Java System Web Server, Sun ONE Web Server, iPlanet and Netscape server installs of PHP on Windows.

From PHP 4.3.3 on you can use PHP scripts with the NSAPI module to generate custom directory listings and error pages. Additional functions for Apache compatibility are also available. For support in current web servers read the note about subrequests.

CGI setup on Sun, iPlanet and Netscape servers

To install PHP as a CGI handler, do the following:

  • Copy php4ts.dll to your systemroot (the directory where you installed Windows)
  • Make a file association from the command line. Type the following two lines:

    assoc .php=PHPScript
    ftype PHPScript=c:\php\php.exe %1 %*

  • In the Netscape Enterprise Administration Server create a dummy shellcgi directory and remove it just after (this step creates 5 important lines in obj.conf and allow the web server to handle shellcgi scripts).
  • In the Netscape Enterprise Administration Server create a new mime type (Category: type, Content-Type: magnus-internal/shellcgi, File Suffix:php).
  • Do it for each web server instance you want PHP to run

More details about setting up PHP as a CGI executable can be found here: » http://benoit.noss.free.fr/php/install-php.html

NSAPI setup on Sun, iPlanet and Netscape servers

To install PHP with NSAPI, do the following:

  • Copy php4ts.dll to your systemroot (the directory where you installed Windows)
  • Make a file association from the command line. Type the following two lines:

    assoc .php=PHPScript
    ftype PHPScript=c:\php\php.exe %1 %*

  • In the Netscape Enterprise Administration Server create a new mime type (Category: type, Content-Type: magnus-internal/x-httpd-php, File Suffix: php).
  • Edit magnus.conf (for servers >= 6) or obj.conf (for servers < 6) and add the following: You should place the lines after mime types init.

    Init fn="load-modules" funcs="php4_init,php4_execute,php4_auth_trans" shlib="c:/php/sapi/php4nsapi.dll"
    Init fn="php4_init" LateInit="yes" errorString="Failed to initialise PHP!" [php_ini="c:/path/to/php.ini"]
    

    (PHP >= 4.3.3) The php_ini parameter is optional but with it you can place your php.ini in your web server configuration directory.

  • Configure the default object in obj.conf (for virtual server classes [Sun Web Server 6.0+] in their vserver.obj.conf): In the <Object name="default"> section, place this line necessarily after all 'ObjectType' and before all 'AddLog' lines:

    Service fn="php4_execute" type="magnus-internal/x-httpd-php" [inikey=value inikey=value ...]
    

    (PHP >= 4.3.3) As additional parameters you can add some special php.ini-values, for example you can set a docroot="/path/to/docroot" specific to the context php4_execute is called. For boolean ini-keys please use 0/1 as value, not "On","Off",... (this will not work correctly), e.g. zlib.output_compression=1 instead of zlib.output_compression="On"

  • This is only needed if you want to configure a directory that only consists of PHP scripts (same like a cgi-bin directory):

    <Object name="x-httpd-php">
    ObjectType fn="force-type" type="magnus-internal/x-httpd-php"
    Service fn=php4_execute [inikey=value inikey=value ...]
    </Object>
    

    After that you can configure a directory in the Administration server and assign it the style x-httpd-php. All files in it will get executed as PHP. This is nice to hide PHP usage by renaming files to .html.

  • Restart your web service and apply changes
  • Do it for each web server instance you want PHP to run

Hinweis: More details about setting up PHP as an NSAPI filter can be found here: » http://benoit.noss.free.fr/php/install-php4.html

Hinweis: The stacksize that PHP uses depends on the configuration of the web server. If you get crashes with very large PHP scripts, it is recommended to raise it with the Admin Server (in the section "MAGNUS EDITOR").

CGI environment and recommended modifications in php.ini

Important when writing PHP scripts is the fact that Sun JSWS/Sun ONE WS/iPlanet/Netscape is a multithreaded web server. Because of that all requests are running in the same process space (the space of the web server itself) and this space has only one environment. If you want to get CGI variables like PATH_INFO, HTTP_HOST etc. it is not the correct way to try this in the old PHP way with getenv() or a similar way (register globals to environment, $_ENV). You would only get the environment of the running web server without any valid CGI variables!

Hinweis: Why are there (invalid) CGI variables in the environment?
Answer: This is because you started the web server process from the admin server which runs the startup script of the web server, you wanted to start, as a CGI script (a CGI script inside of the admin server!). This is why the environment of the started web server has some CGI environment variables in it. You can test this by starting the web server not from the administration server. Use the command line as root user and start it manually - you will see there are no CGI-like environment variables.

Simply change your scripts to get CGI variables in the correct way for PHP 4.x by using the superglobal $_SERVER. If you have older scripts which use $HTTP_HOST, etc., you should turn on register_globals in php.ini and change the variable order too (important: remove "E" from it, because you do not need the environment here):

variables_order = "GPCS"
register_globals = On

Special use for error pages or self-made directory listings (PHP >= 4.3.3)

You can use PHP to generate the error pages for "404 Not Found" or similar. Add the following line to the object in obj.conf for every error page you want to overwrite:

Error fn="php4_execute" code=XXX script="/path/to/script.php" [inikey=value inikey=value...]

where XXX is the HTTP error code. Please delete any other Error directives which could interfere with yours. If you want to place a page for all errors that could exist, leave the code parameter out. Your script can get the HTTP status code with $_SERVER['ERROR_TYPE'].

Another possibility is to generate self-made directory listings. Just create a PHP script which displays a directory listing and replace the corresponding default Service line for type="magnus-internal/directory" in obj.conf with the following:

Service fn="php4_execute" type="magnus-internal/directory" script="/path/to/script.php" [inikey=value inikey=value...]

For both error and directory listing pages the original URI and translated URI are in the variables $_SERVER['PATH_INFO'] and $_SERVER['PATH_TRANSLATED'].

Note about nsapi_virtual() and subrequests (PHP >= 4.3.3)

The NSAPI module now supports the nsapi_virtual() function (alias: virtual()) to make subrequests on the web server and insert the result in the web page. The problem is, that this function uses some undocumented features from the NSAPI library.

Under Unix this is not a problem, because the module automatically looks for the needed functions and uses them if available. If not, nsapi_virtual() is disabled.

Under Windows limitations in the DLL handling need the use of a automatic detection of the most recent ns-httpdXX.dll file. This is tested for servers till version 6.1. If a newer version of the Sun server is used, the detection fails and nsapi_virtual() is disabled.

If this is the case, try the following: Add the following parameter to php4_init in magnus.conf/obj.conf:

Init fn=php4_init ... server_lib="ns-httpdXX.dll"

where XX is the correct DLL version number. To get it, look in the server-root for the correct DLL name. The DLL with the biggest filesize is the right one.

You can check the status by using the phpinfo() function.

Hinweis: But be warned: Support for nsapi_virtual() is EXPERIMENTAL!!!



OmniHTTPd Server

This section contains notes and hints specific to » OmniHTTPd on Windows.

Hinweis: You should read the manual installation steps first!

Warnung

Wenn Sie das CGI-Setup verwenden, ist Ihr Server für einige mögliche Angriffe anfällig. Wie Sie sich vor diesen Angriffen schützen können, entnehmen Sie bitte dem Kapitel über CGI-Sicherheit.

You need to complete the following steps to make PHP work with OmniHTTPd. This is a CGI executable setup. SAPI is supported by OmniHTTPd, but some tests have shown that it is not so stable to use PHP as an ISAPI module.

Hinweis: Important for CGI users
Read the faq on cgi.force_redirect for important details. This directive needs to be set to 0.

  1. Install OmniHTTPd server.

  2. Right click on the blue OmniHTTPd icon in the system tray and select Properties

  3. Click on Web Server Global Settings

  4. On the 'External' tab, enter: virtual = .php | actual = c:\php\php.exe (use php-cgi.exe if installing PHP 5), and use the Add button.

  5. On the Mime tab, enter: virtual = wwwserver/stdcgi | actual = .php, and use the Add button.

  6. Click OK

Repeat steps 2 - 6 for each extension you want to associate with PHP.

Hinweis: Some OmniHTTPd packages come with built in PHP support. You can choose at setup time to do a custom setup, and uncheck the PHP component. We recommend you to use the latest PHP binaries. Some OmniHTTPd servers come with PHP 4 beta distributions, so you should choose not to set up the built in support, but install your own. If the server is already on your machine, use the Replace button in Step 4 and 5 to set the new, correct information.



Sambar Server on Microsoft Windows

This section contains notes and hints specific to the » Sambar Server for Windows.

Hinweis: You should read the manual installation steps first!

This list describes how to set up the ISAPI module to work with the Sambar server on Windows.

  • Find the file called mappings.ini (in the config directory) in the Sambar install directory.

  • Open mappings.ini and add the following line under [ISAPI]:

    Beispiel #1 ISAPI configuration of Sambar

    #for PHP 4
    *.php = c:\php\php4isapi.dll
    
    #for PHP 5
    *.php = c:\php\php5isapi.dll
    

    (This line assumes that PHP was installed in c:\php.)

  • Now restart the Sambar server for the changes to take effect.

Hinweis: If you intend to use PHP to communicate with resources which are held on a different computer on your network, then you will need to alter the account used by the Sambar Server Service. The default account used for the Sambar Server Service is LocalSystem which will not have access to remote resources. The account can be amended by using the Services option from within the Windows Control Panel Administation Tools.



Xitami on Microsoft Windows

This section contains notes and hints specific to » Xitami on Windows.

Hinweis: You should read the manual installation steps first!

This list describes how to set up the PHP CGI binary to work with Xitami on Windows.

Hinweis: Important for CGI users
Read the faq on cgi.force_redirect for important details. This directive needs to be set to 0. If you want to use $_SERVER['PHP_SELF'] you have to enable the cgi.fix_pathinfo directive.

Warnung

Wenn Sie das CGI-Setup verwenden, ist Ihr Server für einige mögliche Angriffe anfällig. Wie Sie sich vor diesen Angriffen schützen können, entnehmen Sie bitte dem Kapitel über CGI-Sicherheit.

  • Make sure the web server is running, and point your browser to xitamis admin console (usually http://127.0.0.1/admin), and click on Configuration.

  • Navigate to the Filters, and put the extension which PHP should parse (i.e. .php) into the field File extensions (.xxx).

  • In Filter command or script put the path and name of your PHP CGI executable i.e. C:\php\php.exe for PHP 4, or C:\php\php-cgi.exe for PHP 5.

  • Press the 'Save' icon.

  • Restart the server to reflect changes.



Building from source

This chapter teaches how to compile PHP from sources on windows, using Microsoft's tools. To compile PHP with cygwin, please refer to Installation auf Unix-Systemen.

This chapter is outdated therefore it's temporarily been removed from the manual. For now, consider the following:



Installation of extensions on Windows

After installing PHP and a web server on Windows, you will probably want to install some extensions for added functionality. You can choose which extensions you would like to load when PHP starts by modifying your php.ini. You can also load a module dynamically in your script using dl().

The DLLs for PHP extensions are prefixed with php_.

Many extensions are built into the Windows version of PHP. This means additional DLL files, and the extension directive, are not used to load these extensions. The Windows PHP Extensions table lists extensions that require, or used to require, additional PHP DLL files. Here's a list of built in extensions:

In PHP 4 (updated PHP 4.3.11): BCMath, Caledar, COM, Ctype, FTP, MySQL, ODBC, Overload, PCRE, Session, Tokenizer, WDDX, XML und Zlib

In PHP 5 (updated PHP 5.0.4), the following changes exist. Built in: DOM, LibXML, Iconv, SimpleXML, SPL und SQLite. And the following are no longer built in: MySQL and Overload.

The default location PHP searches for extensions is C:\php4\extensions in PHP 4 and C:\php5 in PHP 5. To change this setting to reflect your setup of PHP edit your php.ini file:

  • You will need to change the extension_dir setting to point to the directory where your extensions lives, or where you have placed your php_*.dll files. For example:

    extension_dir = C:\php\extensions

  • Enable the extension(s) in php.ini you want to use by uncommenting the extension=php_*.dll lines in php.ini. This is done by deleting the leading ; from the extension you want to load.

    Beispiel #1 Enable Bzip2 extension for PHP-Windows

    // change the following line from ...
    ;extension=php_bz2.dll
    
    // ... to
    extension=php_bz2.dll

  • Some of the extensions need extra DLLs to work. Couple of them can be found in the distribution package, in the C:\php\dlls\ folder in PHP 4 or in the main folder in PHP 5, but some, for example Oracle (php_oci8.dll) require DLLs which are not bundled with the distribution package. If you are installing PHP 4, copy the bundled DLLs from C:\php\dlls folder to the main C:\php folder. Don't forget to include C:\php in the system PATH (this process is explained in a separate FAQ entry).

  • Some of these DLLs are not bundled with the PHP distribution. See each extensions documentation page for details. Also, read the manual section titled Installation of PECL extensions for details on PECL. An increasingly large number of PHP extensions are found in PECL, and these extensions require a separate download.

Hinweis: If you are running a server module version of PHP remember to restart your web server to reflect your changes to php.ini.

The following table describes some of the extensions available and required additional dlls.

PHP Extensions
Extension Description Notes
php_bz2.dll bzip2 compression functions None
php_calendar.dll Calendar conversion functions Built in since PHP 4.0.3
php_crack.dll Crack functions None
php_ctype.dll ctype family functions Built in since PHP 4.3.0
php_curl.dll CURL, Client URL library functions Requires: libeay32.dll, ssleay32.dll (bundled)
php_dba.dll DBA: DataBase (dbm-style) Abstraction layer functions None
php_dbase.dll dBase functions None
php_dbx.dll dbx functions  
php_domxml.dll DOM XML functions PHP <= 4.2.0 requires: libxml2.dll (bundled) PHP >= 4.3.0 requires: iconv.dll (bundled)
php_dotnet.dll .NET functions PHP <= 4.1.1
php_exif.dll EXIF functions php_mbstring.dll. And, php_exif.dll must be loaded after php_mbstring.dll in php.ini.
php_fbsql.dll FrontBase functions PHP <= 4.2.0
php_fdf.dll FDF: Forms Data Format functions. Requires: fdftk.dll (bundled)
php_filepro.dll filePro functions Read-only access
php_ftp.dll FTP functions Built-in since PHP 4.0.3
php_gd.dll GD library image functions Removed in PHP 4.3.2. Also note that truecolor functions are not available in GD1, instead, use php_gd2.dll.
php_gd2.dll GD library image functions GD2
php_gettext.dll Gettext functions PHP <= 4.2.0 requires gnu_gettext.dll (bundled), PHP >= 4.2.3 requires libintl-1.dll, iconv.dll (bundled).
php_hyperwave.dll HyperWave functions None
php_iconv.dll ICONV characterset conversion Requires: iconv-1.3.dll (bundled), PHP >=4.2.1 iconv.dll
php_ifx.dll Informix functions Requires: Informix libraries
php_iisfunc.dll IIS management functions None
php_imap.dll IMAP POP3 and NNTP functions None
php_ingres.dll Ingres functions Requires: Ingres libraries
php_interbase.dll InterBase functions Requires: gds32.dll (bundled)
php_java.dll Java functions PHP <= 4.0.6 requires: jvm.dll (bundled)
php_ldap.dll LDAP functions PHP <= 4.2.0 requires libsasl.dll (bundled), PHP >= 4.3.0 requires libeay32.dll, ssleay32.dll (bundled)
php_mbstring.dll Multi-Byte String functions None
php_mcrypt.dll Mcrypt Encryption functions Requires: libmcrypt.dll
php_mhash.dll Mhash functions PHP >= 4.3.0 requires: libmhash.dll (bundled)
php_mime_magic.dll Mimetype functions Requires: magic.mime (bundled)
php_ming.dll Ming functions for Flash None
php_msql.dll mSQL functions Requires: msql.dll (bundled)
php_mssql.dll MSSQL functions Requires: ntwdblib.dll (bundled)
php_mysql.dll MySQL functions PHP >= 5.0.0, requires libmysql.dll (bundled)
php_mysqli.dll MySQLi functions PHP >= 5.0.0, requires libmysql.dll (libmysqli.dll in PHP <= 5.0.2) (bundled)
php_oci8.dll Oracle 8 functions Requires: Oracle 8.1+ client libraries
php_openssl.dll OpenSSL functions Requires: libeay32.dll (bundled)
php_overload.dll Object overloading functions Built in since PHP 4.3.0
php_pdf.dll PDF functions None
php_pgsql.dll PostgreSQL functions None
php_printer.dll Printer functions None
php_shmop.dll Shared Memory functions None
php_snmp.dll SNMP get and walk functions NT only!
php_soap.dll SOAP functions PHP >= 5.0.0
php_sockets.dll Socket functions None
php_sybase_ct.dll Sybase functions Requires: Sybase client libraries
php_tidy.dll Tidy functions PHP >= 5.0.0
php_tokenizer.dll Tokenizer functions Built in since PHP 4.3.0
php_w32api.dll W32api functions None
php_xmlrpc.dll XML-RPC functions PHP >= 4.2.1 requires: iconv.dll (bundled)
php_xslt.dll XSLT functions PHP <= 4.2.0 requires sablot.dll, expat.dll (bundled). PHP >= 4.2.1 requires sablot.dll, expat.dll, iconv.dll (bundled).
php_yaz.dll YAZ functions Requires: yaz.dll (bundled)
php_zip.dll Zip File functions Read only access
php_zlib.dll ZLib compression functions Built in since PHP 4.3.0



Command Line PHP on Microsoft Windows

This section contains notes and hints specific to getting PHP running from the command line for Windows.

Hinweis: You should read the manual installation steps first!

Getting PHP to run from the command line can be performed without making any changes to Windows.

C:\PHP5\php.exe -f "C:\PHP Scripts\script.php" -- -arg1 -arg2 -arg3

But there are some easy steps that can be followed to make this simpler. Some of these steps should already have been taken, but are repeated here to be able to provide a complete step-by-step sequence.

  • Add the location of the PHP executable (php.exe, php-win.exe or php-cli.exe depending upon your PHP version and display preferences) to the PATH environment variable. Read more about how to add your PHP directory to PATH in the corresponding FAQ entry.

  • Add the .PHP extension to the PATHEXT environment variable. This can be done at the same time as amending the PATH environment variable. Follow the same steps as described in the FAQ but amend the PATHEXT environment variable rather than the PATH environment variable.

    Hinweis: The position in which you place the .PHP will determine which script or program is executed when there are matching filenames. For example, placing .PHP before .BAT will cause your script to run, rather than the batch file, if there is a batch file with the same name.

  • Associate the .PHP extension with a file type. This is done by running the following command:

    assoc .php=phpfile
    

  • Associate the phpfile file type with the appropriate PHP executable. This is done by running the following command:

    ftype phpfile="C:\PHP5\php.exe" -f "%1" -- %~2
    

Following these steps will allow PHP scripts to be run from any directory without the need to type the PHP executable or the .PHP extension and all parameters will be supplied to the script for processing.

The example below details some of the registry changes that can be made manually.

Beispiel #1 Registry changes

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\.php]
@="phpfile"
"Content Type"="application/php"

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\phpfile]
@="PHP Script"
"EditFlags"=dword:00000000
"BrowserFlags"=dword:00000008
"AlwaysShowExt"=""

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\phpfile\DefaultIcon]
@="C:\\PHP5\\php-win.exe0"

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\phpfile\shell]
@="Open"

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\phpfile\shell\Open]
@="&Open"

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\phpfile\shell\Open\command]
@="\"C:\\PHP5\\php.exe\" -f \"%1\" -- %~2"

With these changes the same command can be written as:

"C:\PHP Scripts\script" -arg1 -arg2 -arg3
or, if your "C:\PHP Scripts" path is in the PATH environment variable:
script -arg1 -arg2 -arg3

Hinweis: There is a small problem if you intend to use this techique and use your PHP scripts as commandline filter, like the example below:

dir | "C:\PHP Scripts\script" -arg1 -arg2 -arg3
or
dir | script -arg1 -arg2 -arg3
You may find that the script simply hangs and nothing is output. To get this operational, you need to make another registry change.
Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\policies\Explorer]
"InheritConsoleHandles"=dword:00000001
Further information regarding this issue can be found in this » Microsoft Knowledgebase Article : 321788.




Installation of PECL extensions

Inhaltsverzeichnis


Introduction to PECL Installations

» PECL is a repository of PHP extensions that are made available to you via the » PEAR packaging system. This section of the manual is intended to demonstrate how to obtain and install PECL extensions.

These instructions assume /your/phpsrcdir/ is the path to the PHP source distribution, and that extname is the name of the PECL extension. Adjust accordingly. These instructions also assume a familiarity with the » pear command. The information in the PEAR manual for the pear command also applies to the pecl command.

To be useful, a shared extension must be built, installed, and loaded. The methods described below provide you with various instructions on how to build and install the extensions, but they do not automatically load them. Extensions can be loaded by adding an extension directive. To this php.ini file, or through the use of the dl() function.

When building PHP modules, it's important to have known-good versions of the required tools (autoconf, automake, libtool, etc.) See the » Anonymous SVN Instructions for details on the required tools, and required versions.



Downloading PECL extensions

There are several options for downloading PECL extensions, such as:

  • The pecl install extname command downloads the extensions code automatically, so in this case there is no need for a separate download.
  • » http://pecl.php.net/ The PECL web site contains information about the different extensions that are offered by the PHP Development Team. The information available here includes: ChangeLog, release notes, requirements and other similar details.
  • pecl download extname PECL extensions that have releases listed on the PECL web site are available for download and installation using the » pecl command. Specific revisions may also be specified.
  • SVN Most PECL extensions also reside in SVN. A web-based view may be seen at » http://svn.php.net/viewvc/pecl/. To download straight from SVN, the following sequence of commands may be used:


    $ svn checkout http://svn.php.net/repository/pecl/extname/trunk extname

  • Windows downloads At this time the PHP project does not compile Windows binaries for PECL extensions. However, to compile PHP under Windows see the chapter titled building PHP for Windows.


Installing a PHP extension on Windows

On Windows, you have two ways to load a PHP extension: either compile it into PHP, or load the DLL. Loading a pre-compiled extension is the easiest and preferred way.

To load an extension, you need to have it available as a ".dll" file on your system. All the extensions are automatically and periodically compiled by the PHP Group (see next section for the download).

To compile an extension into PHP, please refer to building from source documentation.

To compile a standalone extension (aka a DLL file), please refer to building from source documentation. If the DLL file is available neither with your PHP distribution nor in PECL, you may have to compile it before you can start using the extension.

Where to find an extension?

PHP extensions are usually called "php_*.dll" (where the star represents the name of the extension) and they are located under the "PHP\ext" ("PHP\extensions" in PHP4) folder.

PHP ships with the extensions most useful to the majority of developers. They are called "core" extensions.

However, if you need functionality not provided by any core extension, you may still be able to find one in PECL. The PHP Extension Community Library (PECL) is a repository for PHP Extensions, providing a directory of all known extensions and hosting facilities for downloading and development of PHP extensions.

If you have developed an extension for your own uses, you might want to think about hosting it on PECL so that others with the same needs can benefit from your time. A nice side effect is that you give them a good chance to give you feedback, (hopefully) thanks, bug reports and even fixes/patches. Before you submit your extension for hosting on PECL, please read http://pecl.php.net/package-new.php.

Which extension to download?

Many times, you will find several versions of each DLL:

  • Different version numbers (at least the first two numbers should match)
  • Different thread safety settings
  • Different processor architecture (x86, x64, ...)
  • Different debugging settings
  • etc.

You should keep in mind that your extension settings should match all the settings of the PHP executable you are using. The following PHP script will tell you all about your PHP settings:

Beispiel #1 phpinfo() call

<?php
phpinfo
();
?>

Or from the command line, run:

drive:\\path\to\php\executable\php.exe -i

Loading an extension

The most common way to load a PHP extension is to include it in your php.ini configuration file. Please note that many extensions are already present in your php.ini and that you only need to remove the semicolon to activate them.

;extension=php_extname.dll
extension=php_extname.dll

However, some web servers are confusing because they do not use the php.ini located alongside your PHP executable. To find out where your actual php.ini resides, look for its path in phpinfo():

Configuration File (php.ini) Path  C:\WINDOWS
Loaded Configuration File   C:\Program Files\PHP\5.2\php.ini

After activating an extension, save php.ini, restart the web server and check phpinfo() again. The new extension should now have its own section.

Resolving problems

If the extension does not appear in phpinfo(), you should check your logs to learn where the problem comes from.

If you are using PHP from the command line (CLI), the extension loading error can be read directly on screen.

If you are using PHP with a web server, the location and format of the logs vary depending on your software. Please read your web server documentation to locate the logs, as it does not have anything to do with PHP itself.

Common problems are the location of the DLL, the value of the " extension_dir" setting inside php.ini and compile-time setting mismatches.

If the problem lies in a compile-time setting mismatch, you probably didn't download the right DLL. Try downloading again the extension with the right settings. Again, phpinfo() can be of great help.



Compiling shared PECL extensions with the pecl command

PECL makes it easy to create shared PHP extensions. Using the » pecl command, do the following:


$ pecl install extname

This will download the source for extname, compile, and install extname.so into your extension_dir. extname.so may then be loaded via php.ini

By default, the pecl command will not install packages that are marked with the alpha or beta state. If no stable packages are available, you may install a beta package using the following command:


$ pecl install extname-beta

You may also install a specific version using this variant:


$ pecl install extname-0.1

Hinweis: After enabling the extension in php.ini, restarting the web service is required for the changes to be picked up.



Compiling shared PECL extensions with phpize

Sometimes, using the pecl installer is not an option. This could be because you're behind a firewall, or it could be because the extension you want to install is not available as a PECL compatible package, such as unreleased extensions from SVN. If you need to build such an extension, you can use the lower-level build tools to perform the build manually.

The phpize command is used to prepare the build environment for a PHP extension. In the following sample, the sources for an extension are in a directory named extname:

$ cd extname
$ phpize
$ ./configure
$ make
# make install

A successful install will have created extname.so and put it into the PHP extensions directory. You'll need to and adjust php.ini and add an extension=extname.so line before you can use the extension.

If the system is missing the phpize command, and precompiled packages (like RPM's) are used, be sure to also install the appropriate devel version of the PHP package as they often include the phpize command along with the appropriate header files to build PHP and its extensions.

Execute phpize --helpto display additional usage information.



Compiling PECL extensions statically into PHP

You might find that you need to build a PECL extension statically into your PHP binary. To do this, you'll need to place the extension source under the php-src/ext/ directory and tell the PHP build system to regenerate its configure script.

$ cd /your/phpsrcdir/ext
$ pecl download extname
$ gzip -d < extname.tgz | tar -xvf -
$ mv extname-x.x.x extname

This will result in the following directory:


/your/phpsrcdir/ext/extname

From here, force PHP to rebuild the configure script, and then build PHP as normal:


$ cd /your/phpsrcdir
$ rm configure
$ ./buildconf --force
$ ./configure --help
$ ./configure --with-extname --enable-someotherext --with-foobar
$ make
$ make install

Hinweis: To run the 'buildconf' script you need autoconf 2.13 and automake 1.4+ (newer versions of autoconf may work, but are not supported).

Whether --enable-extname or --with-extname is used depends on the extension. Typically an extension that does not require external libraries uses --enable. To be sure, run the following after buildconf:


$ ./configure --help | grep extname




Problems?

Inhaltsverzeichnis


Read the FAQ

Some problems are more common than others. The most common ones are listed in the PHP FAQ, part of this manual.



Other problems

If you are still stuck, someone on the PHP installation mailing list may be able to help you. You should check out the archive first, in case someone already answered someone else who had the same problem as you. The archives are available from the support page on » http://www.php.net/support.php. To subscribe to the PHP installation mailing list, send an empty mail to » php-install-subscribe@lists.php.net. The mailing list address is » php-install@lists.php.net.

If you want to get help on the mailing list, please try to be precise and give the necessary details about your environment (which operating system, what PHP version, what web server, if you are running PHP as CGI or a server module, Safe Mode, etc.), and preferably enough code to make others able to reproduce and test your problem.



Bug reports

If you think you have found a bug in PHP, please report it. The PHP developers probably don't know about it, and unless you report it, chances are it won't be fixed. You can report bugs using the bug-tracking system at » http://bugs.php.net/. Please do not send bug reports in mailing list or personal letters. The bug system is also suitable to submit feature requests.

Read the » How to report a bug document before submitting any bug reports!




Laufzeiteinstellungen

Inhaltsverzeichnis


Die Konfigurationsdatei

Die Konfigurationsdatei wird beim Start von PHP eingelesen. Für die Servermodul-Versionen von PHP geschieht dies nur einmal beim Start des Webservers. Für die CGI- und CLI-Versionen geschieht dies bei jedem Aufruf.

Nach der php.ini wird an folgenden Orten in der angegebenen Reihenfolge gesucht:

  • Spezielle Orte für SAPI-Module (PHPIniDir-Direktive im Apache2, -c Kommandozeilenparameter in CGI in CLI, php_ini-Parameter in NSAPI, PHP_INI_PATH-Umgebungsvariable im THTTPD)

  • Die PHPRC-Umgebungsvariable. Vor PHP 5.2.0 wurde dies nach dem unten angegebenen Registrierungsschlüssel geprüft.

  • Seit PHP 5.3.0 kann die Position der php.ini-Datei für verschiedene Versionen von PHP gesetzt werden. Die folgenden Registrierungsschlüssel werden in der angegebenen Reihenfolge durchsucht: [HKEY_LOCAL_MACHINE\SOFTWARE\PHP\x.y.z], [HKEY_LOCAL_MACHINE\SOFTWARE\PHP\x.y] und [HKEY_LOCAL_MACHINE\SOFTWARE\PHP\x], wobei x, y und z die Major-, Minor- und Release-Versionen von PHP darstellen. Falls ein Wert für IniFilePath in diesen Schlüsseln existiert, so wird der zuerst gefundene als Position der php.ini verwendet (nur unter Windows).

  • {HKEY_LOCAL_MACHINE\SOFTWARE\PHP}, Wert von IniFilePath (nur unter Windows)

  • Aktuelles Arbeitsverzeichnis (außer CLI)

  • Das Webserververzeichnis (für SAPI-Module) oder das PHP-Verzeichnis (andernfalls in Windows)

  • Windows-Verzeichnis (C:\windows oder C:\winnt) (unter Windows) oder die --with-config-file-path Kompilierungsoption

Falls die Datei php-SAPI.ini existiert (wobei SAPI die verwendete SAPI ist, was als Dateinamen z.B. php-cli.ini oder php-apache.ini ergibt), wird diese anstelle der php.ini verwendet. Der Name der SAPI kann durch php_sapi_name() ermittelt werden.

Hinweis: Der Apache-Webserver wechselt beim Start das Arbeitsverzeichnis in das Wurzelverzeichnis, weshalb PHP versucht, die php.ini aus dem Wurzelverzeichnis zu lesen, wenn diese existiert.

Die Optionen der php.ini für Extensions werden auf den Handbuchseiten der jeweiligen Extensions behandelt. Die Beschreibung der Core-php.ini-Einstellungen ist im Anhang verfügbar. Es werden jedoch wahrscheinlich nicht alle PHP-Direktiven im Handbuch erläutert. Für eine komplette Liste der in Ihrer PHP-Version verfügbaren Einstellungen lesen Sie bitte die gut kommentierte php.ini. Möglicherweise kann die » aktuellste php.ini aus unserem CVS ebenfalls hilfreich sein.

Beispiel #1 php.ini-Beispiel

; Jeder Text in einer Zeile nach einem Semikolon, welches nicht
; in Anführungszeichen steht, wird ignoriert
[php] ; Abschnittsmarkierungen (Text in eckigen Klammern) werden ebenfalls ignoriert
; Boolesche Werte können auf einen der folgenden Werte eingestellt werden:
;      true, on, yes
; oder false, off, no, none
register_globals = off
track_errors = yes

; Sie können Zeichenketten in Anführungszeichen einschließen
include_path = ".:/usr/local/lib/php"

; Backslashes werden wie alle anderen Zeichen behandelt
include_path = ".;c:\php\lib"

Seit PHP 5.1.0 ist es möglich, sich auf bereits definierte .ini-Variablen innerhalb der .ini-Dateien zu beziehen. Zum Beispiel: open_basedir = ${open_basedir}":/new/dir".



.user.ini-Dateien

Seit PHP 5.3.0 bietet PHP Unterstützung für INI-Dateien im .htaccess-Format auf Verzeichnisebene. Diese Dateien werden nur nur durch die CGI/FastCGI-SAPI verarbeitet. Durch diese Funktionalität wird die htscanner-PECL-Erweiterung obsolet. Falls Sie den Apache benutzen, sollten Sie daher .htaccess-Dateien benutzen.

Zusätzlich zur Haupt-php.ini-Datei sucht PHP auch nach INI-Dateien in Verzeichnissen, die oberhalb des Verzeichnisses der gerade angeforderten PHP-Datei liegen - bis hin zum aktuellen "document root" (wie in $_SERVER['DOCUMENT_ROOT'] konfiguriert). Nur INI-Einstellungen mit den Modi PHP_INI_PERDIR und PHP_INI_USER werden als .user.ini-INI-Dateien erkannt.

Zwei neue INI-Direktiven, user_ini.filename und user_ini.cache_ttl, steuern die Nutzung der Benutzer-INI-Dateien.

user_ini.filename setzt den Namen der Datei, die von PHP in jedem Verzeichnis gesucht wird; falls dies auf eine leere Zeichenkette gesetzt wird, sucht PHP nach keiner Datei. Der Standardwert ist .user.ini.

user_ini.cache_ttl steuert, wie oft die Benutzer-INI-Dateien neu eingelesen werden. Der Standardwert beträgt 300 Sekunden (5 Minuten).



Wo Konfigurationseinstellungen gesetzt werden können

Diese Modi bestimmen wann und wo eine PHP-Direktive gesetzt oder nicht gesetzt werden kann. Jede Direktive im Handbuch verweist auf einen dieser Modi. Zum Beispiel können einige Einstellungen in einem PHP-Skript mittels ini_set() gesetzt werden, während andere nur über die php.ini oder httpd.conf gesetzt werden können.

Ein Beispiel ist die output_buffering-Einstellung. Wegen PHP_INI_PERDIR kann sie nicht mittels ini_set() gesetzt werden. Die display_errors-Einstellung hingegegen kann wegen PHP_INI_ALL überall gesetzt werden, also auch mittels ini_set().

Definition der PHP_INI_*-Modi
Modus Bedeutung
PHP_INI_USER Eintrag kann in Benutzerskripten (z.B. mittels ini_set()) oder in der Windows-Registry gesetzt werden
PHP_INI_PERDIR Eintrag kann in der php.ini, .htaccess oder httpd.conf gesetzt werden
PHP_INI_SYSTEM Eintrag kann in der php.ini oder httpd.conf gesetzt werden
PHP_INI_ALL Eintrag kann überall gesetzt werden



Wie man Konfigurationseinstellungen ändert

PHP läuft als Apachemodul

Wenn man PHP als Apachemodul verwendet, kann man die Konfigurationseinstellungen mittels Direktiven in den Apache-Konfigurationsdateien (z.B. httpd.conf) und .htaccess-Dateien ändern. Dafür benötigt man "AllowOverride Options"- oder "AllowOverride All"-Privilegien.

Es gibt verschiedene Apachedirektiven, die es erlauben, die PHP-Konfiguration aus den Apache-Konfigurationsdateien heraus zu ändern. Für eine Liste von Direktiven, die als PHP_INI_ALL, PHP_INI_PERDIR, oder PHP_INI_SYSTEM definiert sind, werfen Sie einen Blick auf den Anhang Liste von php.ini Einstellungen.

php_value Name Wert

Setzt den Wert der angegebenen Direktive. Kann nur für Direktiven mit den Typen PHP_INI_ALL und PHP_INI_PERDIR verwendet werden. Um einen vorher gesetzten Wert zu löschen, verwenden Sie none als Wert.

Hinweis: Verwenden Sie php_value nicht, um boolesche Werte zu setzen. php_flag (siehe unten) sollte stattdessen verwendet werden.

php_flag Name on|off

Setzt eine boolesche Konfigurationsdirektive. Kann nur für Direktiven mit den Typen PHP_INI_ALL und PHP_INI_PERDIR verwendet werden.

php_admin_value Name Walue

Setzt den Wert der angegebenen Direktive. Dies kann nicht in .htaccess-Dateien verwendet werden. Jeder Direktiventyp, der mit php_admin_value gesetzt wird, kann nicht durch .htaccess-Direktiven oder mit ini_set() überschrieben werden. Um einen vorher gesetzten Wert zu löschen, verwenden Sie none als Wert.

php_admin_flag Name on|off

Setzt eine boolesche Konfigurationsdirektive. Dies kann nicht in .htaccess-Dateien verwendet werden. Jeder Direktiventyp, der mit php_admin_value gesetzt wird, kann nicht durch .htaccess-Direktiven überschrieben werden. Used to set a boolean configuration directive.

Beispiel #1 Apache-Konfigurationsbeispiel

<IfModule mod_php5.c>
  php_value include_path ".:/usr/local/lib/php"
  php_admin_flag safe_mode on
</IfModule>
<IfModule mod_php4.c>
  php_value include_path ".:/usr/local/lib/php"
  php_admin_flag safe_mode on
</IfModule>

Achtung

PHP-Konstanten existieren nicht außerhalb von PHP. So kann man z.B. in der httpd.conf nicht PHP-Konstanten wie E_ALL oder E_NOTICE verwenden, um den Wert der error_reporting-Direktive zu ändern, da diese keine Bedeutung haben und als 0 ausgewertet werden. Verwenden Sie stattdessen die zugehörigen Bitmasken-Werte direkt. Diese Konstanten können in der php.ini verwendet werden.

Die PHP-Konfiguration mit der Windows Registry ändern

Wenn Sie PHP unter Windows einsetzen, können Sie die Konfigurationseinstellungen für jedes einzelne Verzeichnis mit der Windows-Registry anpassen. Die Werte der Konfiguration werden unterhalb des Registrierungsschlüssels HKLM\SOFTWARE\PHP\Per Directory Values in den zum Verzeichnisnamen passenden Unterschlüssel gespeichert.Zum Beispiel würden Werte für das Verzeichnis c:\inetpub\wwwroot im Registrierungsschlüssel HKLM\SOFTWARE\PHP\Per Directory Values\c\inetpub\wwwroot gespeichert werden. Die Einstellungen für dieses Verzeichnis wären für alle Skripte aktiv, die in diesem Verzeichnis oder einem seiner Unterverzeichnisse laufen. Die Werte in diesem Schlüssel sollten den Namen eine PHP- Konfigurationsdirektive und einen Zeichenkettenwert haben. Konstenten in den Werten werden nicht ausgewertet. Es können jedoch nur Werte, die in PHP_INI_USER änderbar sind, auf diese Weise gesetzt werden, nicht als PHP_INI_PERDIR deklarierte Werte.

Andere Zugänge zu PHP

Egal wie Sie PHP betreiben, Sie können bestimmte Werte zur Laufzeit Ihrer Skripte mittels ini_set() setzen. Werfen Sie dazu einen Blick auf die Dokumentation von ini_set().

Wenn Sie an einer kompletten Liste von Konfigurationseinstellungen Ihres Systems inklusive deren aktuellen Werten interessiert sind, können Sie die Funktion phpinfo() ausführen und die daraus resultierende Seite betrachten. Sie können auf die Werte einzelner Konfigurationsdirektiven zur Laufzeit mittels ini_get() oder get_cfg_var() zugreifen.





Sprachreferenz


Grundlagen der Syntax

Inhaltsverzeichnis


Den HTML-Bereich der Datei verlassen

Wenn PHP eine Datei parst, sucht es nach öffnenden und schließenden Tags, die PHP anweisen, den dazwischen befindlichen Code zu interpretieren. Das Parsen auf diese Art erlaubt Ihnen, PHP in allen möglichen Arten von unterschiedlichen Dokumenten einzubinden, da alles außerhalb des Paars aus öffnendem und schließendem Tag vom Parser ignoriert wird. In den meisten Fällen werden Sie wie im folgenden Beispiel PHP in HTML-Dokumente eingebettet finden.

<p>Das hier wird ignoriert werden.</p>
<?php echo 'Wohingegen das hier geparst werden wird.'?>
<p>Dies wird ebenfalls ignoriert.</p>

Sie können aber auch komplexere Strukturen verwenden:

Beispiel #1 Fortgeschrittenes Erweitern

<?php
if ($ausdruck) {
    
?>
    <strong>Dies ist wahr.</strong>
    <?php
} else {
    
?>
    <strong>Dies ist falsch.</strong>
    <?php
}
?>

Dies arbeitet wie erwartet, da PHP, wenn es auf ein schließendes >?-Tag trifft, einfach beginnt, alles folgende auszugeben, bis es wieder auf einen öffnenden Tag stößt (mit Ausnahme eines direkt folgenden Newline-Zeichens - siehe auch Abschnitt Abgrenzung von Anweisungen). Das hier angegebene Beispiel ist natürlich nur ausgedacht, aber für die Ausgabe von großen Textblöcken ist der Ausstieg aus dem Parse-Modus generell effizienter, als den gesamten Text durch echo() oder print() zu jagen.

Es gibt vier unterschiedliche Paare öffnender und schließender Tags, die in PHP verwendet werden können. Zwei davon, <?php ?> und <script language="php"> </script>, sind immer verfügbar. Die anderen beiden sind Short-Tags und ASP-Tags, die über das php.ini-Konfigurationsfile ein- und ausgeschaltet werden können. Das bedeutet, wenn einige Leute Short-Tags und ASP-Tags bequem finden, sind die daraus resultierenden Skripte nicht überall einsetzbar, so dass diese Tags grundsätzlich nicht empfehlenswert sind.

Hinweis: Beachten Sie auch, dass Sie, wenn Sie PHP in XML oder XHTML einbinden wollen, die <?php ?>-Tags verwenden müssen, um keine Parserfehler aufgrund vermischter Standards zu provozieren.

Beispiel #2 Die öffnenden und schließenden Tags von PHP

1.  <?php echo
      
'wenn Sie XHTML- oder XML-Dokumente ausliefern wollen, machen Sie es so'?>

2.  <script language="php">
        
echo 'manche Editoren(wie FrontPage) moegen
              keine Verarbeitungsanweisungen'
;
    
</script>

3.  <? echo 'das ist das Einfachste, eine SGML-Verarbeitungsanweisung'?>

4.  <% echo 'Optional koennen Sie auch Tags im ASP-Stil verwenden'; %>
    <%= $variable; # Das ist ein Abkuerzung fuer "<% echo . . ." %>

Während die Tags in Beispiel eins und zwei jederzeit verfügbar sind, ist Beispiel eins das meist verwendete und grundsätzlich empfohlene von beiden.

Short-Tags (Beispiel drei) sind nur verfügbar, wenn sie via short_open_tag-Direktive im php.ini-Konfigurationsfile eingeschaltet wurden, oder wenn PHP mit --enable-short-tags konfiguriert wurde.

ASP-Tags (Beispiel vier) sind nur verfügbar, wenn sie mittels der asp_tags-Direktive im php.ini Konfigurationsfile eingeschaltet wurden.

Hinweis: Die Verwendung der Short-Tags sollten Sie vermeiden, wenn Sie Applikationen oder Bibliotheken entwickeln, die für die Weitergabe oder den Einsatz auf nicht Ihrer Kontrolle unterstehenden PHP-Servern bestimmt sind, da es sein kann, dass Short-Tags auf dem Zielsystem nicht unterstützt werden. Um portablen, weiterverteilbaren Code zu haben, verwenden Sie keine Short-Tags.



Abgrenzung von Anweisungen

Wie in C oder Perl verlangt PHP, dass Anweisungen am Ende jedes Statements mit einem Semikolon beendet werden. Der schließende Tag eines Blocks mit PHP-Code impliziert automatisch ein Semikolon, Sie brauchen daher kein abschließendes Semikolon in der letzten Zeile des PHP-Blocks zu setzen. Der schließende Tag für den Block fügt das direkt nachfolgende Zeilenumbruch-Zeichen ein, wenn es vorhanden ist.

<?php
    
echo 'Dies ist ein Test';
?>

<?php echo 'Dies ist ein Test' ?>

<?php echo 'Wir ließen den letzen schließenden Tag weg';

Hinweis: Der schließende Tag eines PHP-Blocks am Ende einer Datei ist optional, und in einigen Fällen ist das Weglassen hilfreich, wenn Sie include() oder require() verwenden, so dass ungewollte Whitespaces nicht am Ende einer Datei auftreten und Sie noch im Stande sind, später weitere Header an die Response hinzuzufügen. Es ist ebenfalls praktisch, wenn Sie Output Buffering verwenden und keine ungewollten Whitespaces am Ende eines durch die eingebundenen Dateien erzeugten Parts sehen wollen.



Kommentare

PHP unterstützt 'C', 'C++' und Unix-Shell-artige (Perl-artige) Kommentare. Zum Beispiel:

<?php
    
echo "Dies ist ein Test"// Dies ist ein einzeiliger Kommentar im C++-Stil
    /* Dies ist ein mehrzeiliger Kommentar
       noch eine weitere Kommentar-Zeile */
    
echo 'Dies ist noch ein Test';
    echo 
'... und ein letzter Test'# Dies ist ein einzeiliger Shell-Kommentar
?>

Die "einzeiligen" Kommentar-Arten kommentieren sämtlichen Text bis zum Zeilenende oder bis zum Ende des aktuellen PHP-Blocks aus, je nachdem, was zuerst eintritt. Das bedeutet, das HTML-Code nach // ..?> oder # ... ?> ausgegeben WIRD: ?> beendet den PHP-Modus und kehrt in den HTML-Modus zurück, so dass sich // oder # nicht nicht darauf auswirkt. Wenn die asp_tags Konfigurations-Direktive eingeschaltet ist, verhält es sich genauso bei // %> und # %>. Jedoch beendet das </script>-Tag den PHP-Modus innerhalb eines einzeiligen Kommentars nicht.

<h1>Dies ist ein  <?php # echo 'einfaches';?> Beispiel.</h1>
<p>Obige Überschrift wird lauten: 'Dies ist ein Beispiel.'.

'C'-artige Kommentare enden am ersten Vorkommen von */. Achten Sie daher darauf, 'C'-artige Kommentare nicht zu verschachteln. Dieser Fehler entsteht leicht, wenn Sie längere Code-Blöcke auskommentieren.

<?php
/*
   echo 'Dies ist ein Test'; /* Dieser Kommentar wird ein Problem verursachen. */
*/
?>




Typen

Inhaltsverzeichnis


Einführung

PHP unterstützt acht primitive Typen.

Vier skalare Typen:

Zwei zusammengesetzte Typen:

Und zuletzt zwei spezielle Typen:

Für die bessere Lesbarkeit führt dieses Handbuch ein paar Pseudo-Typen ein:

Sowie die Pseudovariable $... .

Sie werden auch ein paar Hinweise auf den Typ "Double" finden. Betrachten Sie Double als dasselbe wie Float. Die beiden Bezeichnungen existieren nur aus historischen Gründen.

Der Typ einer Variablen wird normalerweise nicht vom Programmierer bestimmt. Zur Laufzeit von PHP wird entschieden, welchen Typs eine Variable ist. Dies ist abhängig vom Zusammenhang, in dem die Variable benutzt wird.

Hinweis: Um den Typ und den Wert eines bestimmten Ausdrucks (Expression) zu überprüfen, können Sie var_dump() benutzen. Wenn Sie zur Fehlersuche einfach nur eine lesbare Darstellung eines Typs benötigen, benutzen Sie gettype(). Um auf einen bestimmten Typ zu prüfen, sollten Sie nicht gettype() benutzen. Stattdessen sollten Sie die is_type Funktionen verwenden. Ein paar Beispiele:

<?php
$a_bool 
TRUE;   // ein Boolean (Wahrheitswert)
$a_str  "foo";  // eine Zeichenkette (String)
$a_str2 'foo';  // eine Zeichenkette (String)
$an_int 12;     // ein Integer (Ganzzahl)

echo gettype($a_bool); // gibt aus:  boolean
echo gettype($a_str);  // gibt aus:  string


// Falls es ein Integer ist, erhöhe ihn um vier
if (is_int($an_int)) {
    
$an_int += 4;
}

// Falls $bool ein String ist, gib ihn aus
// (gibt überhaupt nichts aus)
if (is_string($a_bool)) {
    echo 
"String: $a_bool";
}
?>

Wenn sie die Umwandlung in einen bestimmten Variablen-Typ erzwingen wollen, erreichen Sie dies entweder durch Typ-Umwandlung (Cast) oder durch Gebrauch der Funktion settype().

Beachten Sie, dass eine Variable abhängig vom Typ, dem die Variable zu dem Zeitpunkt entspricht, in bestimmten Situationen unterschiedlich ausgewertet werden kann. Weitere Informationen entnehmen Sie dem Abschnitt zur Typ-Veränderung (Type Juggling). Schauen Sie sich außerdem Die PHP Typ-Vergleichstabellen an, wenn Sie an Beispielen verschiedener typenbezogener Vergleiche interessiert sind.



Booleans

Dies ist der einfachste Typ. Ein boolean Ausdruck ist ein Wahrheitswert der entweder TRUE (wahr) oder FALSE (falsch) sein kann.

Hinweis: Der boolean Typ wurde in PHP 4 eingeführt.

Syntax

Ein boolean Wert wird über die Schlüsselworte TRUE und FALSE spezifiziert, Groß- und Kleinschreibung ist dabei nicht von Bedeutung.

<?php
$foo 
True// weist $foo den Wert TRUE zu
?>

Normalerweise wird ein boolean von einem Operator zurückgegeben und an eine Kontrollstruktur weitergegeben.

<?php
// == ist ein Operator der auf Gleichheit prüft
// und ein boolean Ergebnis zurückgibt
if ($action == "show_version") {
    echo 
"Die Version ist 1.23";
}

// die Angabe von '== TRUE' ist hier nicht nötig
if ($show_separators == TRUE) {
    echo 
"<hr>\n";
}

// ... stattdessen funktioniert auch einfach das folgende:
if ($show_separators) {
    echo 
"<hr>\n";
}
?>

Converting to boolean

To explicitly convert a value to boolean, use the (bool) or (boolean) casts. However, in most cases the cast is unncecessary, since a value will be automatically converted if an operator, function or control structure requires a boolean argument.

Siehe auch Typumwandlungen.

Bei der Konvertierung zum Typ boolean gelten die folgenden Werte als FALSE:

  • boolean FALSE selbst
  • integer 0 (zero)
  • float 0.0 (zero)
  • Der leere string, und der string "0"
  • Ein array ohne Elemente
  • Ein object ohne Eigenschaftsvariablen (nur PHP 4)
  • Der spezielle Typ NULL (inklusive nicht gesetzter Variablen)
  • SimpleXML Objekte die aus leeren Tags erzeugt wurden.

Jeder andere Wert wird als TRUE angenommen (inklusive jeglicher resource Werte).

Warnung

-1 gilt als TRUE wie jeder andere Integerwert ungleich 0 (egal ob positiv oder negativ)!

<?php
var_dump
((bool) "");        // bool(false)
var_dump((bool) 1);         // bool(true)
var_dump((bool) -2);        // bool(true)
var_dump((bool) "foo");     // bool(true)
var_dump((bool) 2.3e5);     // bool(true)
var_dump((bool) array(12)); // bool(true)
var_dump((bool) array());   // bool(false)
var_dump((bool) "false");   // bool(true)
?>


Integers

An integer is a number of the set Z = {..., -2, -1, 0, 1, 2, ...}.

See also:

Syntax

Integers can be specified in decimal (base 10), hexadecimal (base 16), or octal (base 8) notation, optionally preceded by a sign (- or +).

To use octal notation, precede the number with a 0 (zero). To use hexadecimal notation precede the number with 0x.

Beispiel #1 Integer literals

<?php
$a 
1234// decimal number
$a = -123// a negative number
$a 0123// octal number (equivalent to 83 decimal)
$a 0x1A// hexadecimal number (equivalent to 26 decimal)
?>

Formally, the structure for integer literals is:

decimal     : [1-9][0-9]*
            | 0

hexadecimal : 0[xX][0-9a-fA-F]+

octal       : 0[0-7]+

integer     : [+-]?decimal
            | [+-]?hexadecimal
            | [+-]?octal

The size of an integer is platform-dependent, although a maximum value of about two billion is the usual value (that's 32 bits signed). PHP does not support unsigned integers. Integer size can be determined using the constant PHP_INT_SIZE, and maximum value using the constant PHP_INT_MAX since PHP 4.4.0 and PHP 5.0.5.

Warnung

If an invalid digit is given in an octal integer (i.e. 8 or 9), the rest of the number is ignored.

Beispiel #2 Octal weirdness

<?php
var_dump
(01090); // 010 octal = 8 decimal
?>

Integer overflow

If PHP encounters a number beyond the bounds of the integer type, it will be interpreted as a float instead. Also, an operation which results in a number beyond the bounds of the integer type will return a float instead.

<?php
$large_number 
=  2147483647;
var_dump($large_number);
// output: int(2147483647)

$large_number =  2147483648;
var_dump($large_number);
// output: float(2147483648)

// it's true also for hexadecimal specified integers between 2^31 and 2^32-1:
var_dump0xffffffff );
// output: float(4294967295)

// this doesn't go for hexadecimal specified integers above 2^32-1:
var_dump0x100000000 );
// output: int(2147483647)

$million 1000000;
$large_number =  50000 $million;
var_dump($large_number);
// output: float(50000000000)
?>
Warnung

Unfortunately, there was a bug in PHP which caused this to not always work correctly when negative numbers were involved. For example, the result of -50000 * $million is -429496728. However, when both operands were positive, there was no problem.

This was fixed in PHP 4.1.0.

There is no integer division operator in PHP. 1/2 yields the float 0.5. The value can be casted to an integer to round it downwards, or the round() function provides finer control over rounding.

<?php
var_dump
(25/7);         // float(3.5714285714286) 
var_dump((int) (25/7)); // int(3)
var_dump(round(25/7));  // float(4) 
?>

Converting to integer

To explicitly convert a value to integer, use either the (int) or (integer) casts. However, in most cases the cast is not needed, since a value will be automatically converted if an operator, function or control structure requires an integer argument. A value can also be converted to integer with the intval() function.

See also: type-juggling.

From booleans

FALSE will yield 0 (zero), and TRUE will yield 1 (one).

From floating point numbers

When converting from float to integer, the number will be rounded towards zero.

If the float is beyond the boundaries of integer (usually +/- 2.15e+9 = 2^31), the result is undefined, since the float doesn't have enough precision to give an exact integer result. No warning, not even a notice will be issued when this happens!

Warnung

Never cast an unknown fraction to integer, as this can sometimes lead to unexpected results.

<?php
echo (int) ( (0.1+0.7) * 10 ); // echoes 7!
?>

See also the warning about float precision.

From strings

See String conversion to numbers

From other types

Achtung

The behaviour of converting to integer is undefined for other types. Do not rely on any observed behaviour, as it can change without notice.



Fließkommazahlen

Fließkommazahlen (auch bekannt als "floats", "doubles" oder "real numbers") können in jeder der folgenden Syntaxformen angegeben werden:

<?php
$a 
1.234
$b 1.2e3
$c 7E-10;
?>

Formell:

LNUM          [0-9]+
DNUM          ([0-9]*[\.]{LNUM}) | ({LNUM}[\.][0-9]*)
EXPONENT_DNUM [+-]?(({LNUM} | {DNUM}) [eE][+-]? {LNUM})

Der Wertebereich für Fließkommawertes ist platformabhängig, alderdings ist ein maximaler Wert von ca. 1.8e308 mit einer Genauigkeit von ca. 14 Nachkommastellen (entsprechend dem 64bit IEEE-Format) üblich.

Warnung

Fließkommagenauigkeit

Es ist typisch das einfache Dezimalbrüche wie 0.1 oder 0.7 nicht ohne kleine Ungenauigkeiten in ihr internes binäres Gegenstück umgewandelt werden können. Dies kann zu verwirrenden Ergebnissen führen, so ergibt floor((0.1+0.7)*10) in der Regel 7 an Stelle der der erwarteten 8 da die interne Repräsentation eher bei 7.9 liegt.

Dies liegt daran das es unmöglich ist bestimmte Werte mit einer endlichen Anzahl von Nachkommenstellen darzustellen. So wird zum Beispiel 1/3 im Dezimalsystem 0.3.

Sie sollten daher Fließkommawerten nicht bis auf die letzte Nachkommastelle trauen und vor allem niemals Fließkommawerte auf exakte Gleichheit prüfen. Wenn Sie höhere Genauigkeit benötigen können Sie die Mathematikfunktionen für beliebige Genauigkeit oder die gmp-Funktionen nutzen.

Umwandlung in Fließkommawerte

Informationen zur Umwandlung von Strings in float finden Sie im Abschnitt Umwandlung von Zeichenketten in Zahlen. Andere Datentypen werden zunächst in einen integer-Wert umgewandelt und von da aus weiter in einen Fließkommawert. Mehr Informationen hierzu finden Sie im Abschnitt Umwandlung in Integerwerte. Beginnend mit PHP 5 wird bei der Umwandlung eines Objects in float eine Hinweismeldung geworfen.



Strings

A string is series of characters. Before PHP 6, a character is the same as a byte. That is, there are exactly 256 different characters possible. This also implies that PHP has no native support of Unicode. See utf8_encode() and utf8_decode() for some basic Unicode functionality.

Hinweis: It is no problem for a string to become very large. PHP imposes no boundary on the size of a string; the only limit is the available memory of the computer on which PHP is running.

Syntax

A string literal can be specified in four different ways:

Single quoted

The simplest way to specify a string is to enclose it in single quotes (the character ').

To specify a literal single quote, escape it with a backslash (\). To specify a literal backslash before a single quote, or at the end of the string, double it (\\). Note that attempting to escape any other character will print the backslash too.

Hinweis: Unlike the two other syntaxes, variables and escape sequences for special characters will not be expanded when they occur in single quoted strings.

<?php
echo 'this is a simple string';

echo 
'You can also have embedded newlines in 
strings this way as it is
okay to do'
;

// Outputs: Arnold once said: "I'll be back"
echo 'Arnold once said: "I\'ll be back"';

// Outputs: You deleted C:\*.*?
echo 'You deleted C:\\*.*?';

// Outputs: You deleted C:\*.*?
echo 'You deleted C:\*.*?';

// Outputs: This will not expand: \n a newline
echo 'This will not expand: \n a newline';

// Outputs: Variables do not $expand $either
echo 'Variables do not $expand $either';
?>

Double quoted

If the string is enclosed in double-quotes ("), PHP will interpret more escape sequences for special characters:

Escaped characters
Sequence Meaning
\n linefeed (LF or 0x0A (10) in ASCII)
\r carriage return (CR or 0x0D (13) in ASCII)
\t horizontal tab (HT or 0x09 (9) in ASCII)
\v vertical tab (VT or 0x0B (11) in ASCII) (since PHP 5.2.5)
\f form feed (FF or 0x0C (12) in ASCII) (since PHP 5.2.5)
\\ backslash
\$ dollar sign
\" double-quote
\[0-7]{1,3} the sequence of characters matching the regular expression is a character in octal notation
\x[0-9A-Fa-f]{1,2} the sequence of characters matching the regular expression is a character in hexadecimal notation

As in single quoted strings, escaping any other character will result in the backslash being printed too. Before PHP 5.1.1, the backslash in \{$var} was not been printed.

The most important feature of double-quoted strings is the fact that variable names will be expanded. See string parsing for details.

Heredoc

A third way to delimit strings is the heredoc syntax: <<<. After this operator, an identifier is provided, then a newline. The string itself follows, and then the same identifier again to close the quotation.

The closing identifier must begin in the first column of the line. Also, the identifier must follow the same naming rules as any other label in PHP: it must contain only alphanumeric characters and underscores, and must start with a non-digit character or underscore.

Warnung

It is very important to note that the line with the closing identifier must contain no other characters, except possibly a semicolon (;). That means especially that the identifier may not be indented, and there may not be any spaces or tabs before or after the semicolon. It's also important to realize that the first character before the closing identifier must be a newline as defined by the local operating system. This is \n on UNIX systems, including Mac OS X. The closing delimiter (possibly followed by a semicolon) must also be followed by a newline.

If this rule is broken and the closing identifier is not "clean", it will not be considered a closing identifier, and PHP will continue looking for one. If a proper closing identifier is not found before the end of the current file, a parse error will result at the last line.

Heredocs can not be used for initializing class members. Use nowdocs instead.

Beispiel #1 Invalid example

<?php
class foo {
    public 
$bar = <<<EOT
bar
EOT;
}
?>

Heredoc text behaves just like a double-quoted string, without the double quotes. This means that quotes in a heredoc do not need to be escaped, but the escape codes listed above can still be used. Variables are expanded, but the same care must be taken when expressing complex variables inside a heredoc as with strings.

Beispiel #2 Heredoc string quoting example

<?php
$str 
= <<<EOD
Example of string
spanning multiple lines
using heredoc syntax.
EOD;

/* More complex example, with variables. */
class foo
{
    var 
$foo;
    var 
$bar;

    function 
foo()
    {
        
$this->foo 'Foo';
        
$this->bar = array('Bar1''Bar2''Bar3');
    }
}

$foo = new foo();
$name 'MyName';

echo <<<EOT
My name is "$name". I am printing some $foo->foo.
Now, I am printing some 
{$foo->bar[1]}.
This should print a capital 'A': \x41
EOT;
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

My name is "MyName". I am printing some foo.
Now I am printing some Bar2.
This should print a capital 'A': \x41

Hinweis: Heredoc support was added in PHP 4.

Nowdoc

Nowdocs are to single-quoted strings what heredocs are to double-quoted strings. A nowdoc is specified similarly to a heredoc, but no parsing is done inside a nowdoc. The construct is ideal for embedding PHP code or other large blocks of text without the need for escaping. It shares some features in common with the SGML &lt;![CDATA[ ]]&gt; construct, in that it declares a block of text which is not for parsing.

A nowdoc is identified with the same <<< seqeuence used for heredocs, but the identifier which follows is enclosed in single quotes, e.g. <<<'EOT'. All the rules for heredoc identifiers also apply to nowdoc identifiers, especially those regarding the appearance of the closing identifier.

Beispiel #3 Nowdoc string quoting example

<?php
$str 
= <<<'EOD'
Example of string
spanning multiple lines
using nowdoc syntax.
EOD;

/* More complex example, with variables. */
class foo
{
    var 
$foo;
    var 
$bar;

    function 
foo()
    {
        
$this->foo 'Foo';
        
$this->bar = array('Bar1''Bar2''Bar3');
    }
}

$foo = new foo();
$name 'MyName';

echo <<<'EOT'
My name is "$name". I am printing some $foo->foo.
Now, I am printing some {$foo->bar[1]}.
This should not print a capital 'A': \x41
EOT;
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

My name is "$name". I am printing some $foo->foo.
Now, I am printing some {$foo->bar[1]}.
This should not print a capital 'A': \x41

Hinweis: Unlike heredocs, nowdocs can be used in any static data context. The typical example is initializing class members or constants:

Beispiel #4 Static data example

<?php
class foo {
    public 
$bar = <<<'EOT'
bar
EOT;
}
?>

Hinweis: Nowdoc support was added in PHP 5.3.0.

Variable parsing

When a string is specified in double quotes or with heredoc, variables are parsed within it.

There are two types of syntax: a simple one and a complex one. The simple syntax is the most common and convenient. It provides a way to embed a variable, an array value, or an object property in a string with a minimum of effort.

The complex syntax was introduced in PHP 4, and can be recognised by the curly braces surrounding the expression.

Simple syntax

If a dollar sign ($) is encountered, the parser will greedily take as many tokens as possible to form a valid variable name. Enclose the variable name in curly braces to explicitly specify the end of the name.

<?php
$beer 
'Heineken';
echo 
"$beer's taste is great"// works; "'" is an invalid character for variable names
echo "He drank some $beers";   // won't work; 's' is a valid character for variable names
echo "He drank some ${beer}s"// works
echo "He drank some {$beer}s"// works
?>

Similarly, an array index or an object property can be parsed. With array indices, the closing square bracket (]) marks the end of the index. The same rules apply to object properties as to simple variables.

<?php
// These examples are specific to using arrays inside of strings.
// When outside of a string, always quote array string keys and do not use
// {braces}.

// Show all errors
error_reporting(E_ALL);

$fruits = array('strawberry' => 'red''banana' => 'yellow');

// Works, but note that this works differently outside a string
echo "A banana is $fruits[banana].";

// Works
echo "A banana is {$fruits['banana']}.";

// Works, but PHP looks for a constant named banana first, as described below.
echo "A banana is {$fruits[banana]}.";

// Won't work, use braces.  This results in a parse error.
echo "A banana is $fruits['banana'].";

// Works
echo "A banana is " $fruits['banana'] . ".";

// Works
echo "This square is $square->width meters broad.";

// Won't work. For a solution, see the complex syntax.
echo "This square is $square->width00 centimeters broad.";
?>

For anything more complex, you should use the complex syntax.

Complex (curly) syntax

This isn't called complex because the syntax is complex, but because it allows for the use of complex expressions.

In fact, any value in the namespace can be included in a string with this syntax. Simply write the expression the same way as it would appeared outside the string, and then wrap it in { and }. Since { can not be escaped, this syntax will only be recognised when the $ immediately follows the {. Use {\$ to get a literal {$. Some examples to make it clear:

<?php
// Show all errors
error_reporting(E_ALL);

$great 'fantastic';

// Won't work, outputs: This is { fantastic}
echo "This is { $great}";

// Works, outputs: This is fantastic
echo "This is {$great}";
echo 
"This is ${great}";

// Works
echo "This square is {$square->width}00 centimeters broad."

// Works
echo "This works: {$arr[4][3]}";

// This is wrong for the same reason as $foo[bar] is wrong  outside a string.
// In other words, it will still work, but only because PHP first looks for a
// constant named foo; an error of level E_NOTICE (undefined constant) will be
// thrown.
echo "This is wrong: {$arr[foo][3]}"

// Works. When using multi-dimensional arrays, always use braces around arrays
// when inside of strings
echo "This works: {$arr['foo'][3]}";

// Works.
echo "This works: " $arr['foo'][3];

echo 
"This works too: {$obj->values[3]->name}";

echo 
"This is the value of the var named $name{${$name}}";

echo 
"This is the value of the var named by the return value of getName(): {${getName()}}";

echo 
"This is the value of the var named by the return value of \$object->getName(): {${$object->getName()}}";
?>

Hinweis: Functions and method calls inside {$} work since PHP 5.

String access and modification by character

Characters within strings may be accessed and modified by specifying the zero-based offset of the desired character after the string using square array brackets, as in $str[42]. Think of a string as an array of characters for this purpose.

Hinweis: Strings may also be accessed using braces, as in $str{42}, for the same purpose. However, this syntax is deprecated as of PHP 6. Use square brackets instead.

Beispiel #5 Some string examples

<?php
// Get the first character of a string
$str 'This is a test.';
$first $str[0];

// Get the third character of a string
$third $str[2];

// Get the last character of a string.
$str 'This is still a test.';
$last $str[strlen($str)-1]; 

// Modify the last character of a string
$str 'Look at the sea';
$str[strlen($str)-1] = 'e';

?>

Hinweis: Accessing variables of other types using [] or {} silently returns NULL.

Useful functions and operators

Strings may be concatenated using the '.' (dot) operator. Note that the '+' (addition) operator will not work for this. See String operators for more information.

There are a number of useful functions for string manipulation.

See the string functions section for general functions, and the regular expression functions or the Perl-compatible regular expression functions for advanced find & replace functionality.

There are also functions for URL strings, and functions to encrypt/decrypt strings (mcrypt and mhash).

Finally, see also the character type functions.

Converting to string

A value can be converted to a string using the (string) cast or the strval() function. String conversion is automatically done in the scope of an expression where a string is needed. This happens when using the echo() or print() functions, or when a variable is compared to a string. The sections on Types and Type Juggling will make the following clearer. See also the settype() function.

A boolean TRUE value is converted to the string "1". Boolean FALSE is converted to "" (the empty string). This allows conversion back and forth between boolean and string values.

An integer or float is converted to a string representing the number textually (including the exponent part for floats). Floating point numbers can be converted using exponential notation (4.1E+6).

Hinweis: The decimal point character is defined in the script's locale (category LC_NUMERIC). See the setlocale() function.

Arrays are always converted to the string "Array"; because of this, echo() and print() can not by themselves show the contents of an array. To view a single element, use a construction such as echo $arr['foo']. See below for tips on viewing the entire contents.

Objects in PHP 4 are always converted to the string "Object". To print the values of object members for debugging reasons, read the paragraphs below. To get an object's class name, use the get_class() function. As of PHP 5, the __toString method is used when applicable.

Resources are always converted to strings with the structure "Resource id #1", where 1 is the unique number assigned to the resource by PHP at runtime. Do not rely upon this structure; it is subject to change. To get a resource's type, use the get_resource_type() function.

NULL is always converted to an empty string.

As stated above, directly converting an array, object, or resource to a string does not provide any useful information about the value beyond its type. See the functions print_r() and var_dump() for more effective means of inspecting the contents of these types.

Most PHP values can also be converted to strings for permanent storage. This method is called serialization, and is performed by the serialize() function. If the PHP engine was built with WDDX support, PHP values can also be serialized as well-formed XML text.

String conversion to numbers

When a string is evaluated in a numeric context, the resulting value and type are determined as follows.

The string will be evaluated as a float if it contains any of the characters '.', 'e', or 'E'. Otherwise, it will be evaluated as an integer.

The value is given by the initial portion of the string. If the string starts with valid numeric data, this will be the value used. Otherwise, the value will be 0 (zero). Valid numeric data is an optional sign, followed by one or more digits (optionally containing a decimal point), followed by an optional exponent. The exponent is an 'e' or 'E' followed by one or more digits.

<?php
$foo 
"10.5";                // $foo is float (11.5)
$foo "-1.3e3";              // $foo is float (-1299)
$foo "bob-1.3e3";           // $foo is integer (1)
$foo "bob3";                // $foo is integer (1)
$foo "10 Small Pigs";       // $foo is integer (11)
$foo "10.2 Little Piggies"// $foo is float (14.2)
$foo "10.0 pigs " 1;          // $foo is float (11)
$foo "10.0 pigs " 1.0;        // $foo is float (11)     
?>

For more information on this conversion, see the Unix manual page for strtod(3).

To test any of the examples in this section, cut and paste the examples and insert the following line to see what's going on:

<?php
echo "\$foo==$foo; type is " gettype ($foo) . "<br />\n";
?>

Do not expect to get the code of one character by converting it to integer, as is done in C. Use the ord() and chr() functions to convert between ASCII codes and characters.



Arrays

An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more. As array values can be other arrays, trees and multidimensional arrays are also possible.

Explanation of those data structures is beyond the scope of this manual, but at least one example is provided for each of them. For more information, look towards the considerable literature that exists about this broad topic.

Syntax

Specifying with array()

An array can be created by the array() language construct. It takes as parameters any number of comma-separated key => value pairs.

array(  key =>  value
     , ...
     )
// key may only be an integer or string
// value may be any value of any type
<?php
$arr 
= array("foo" => "bar"12 => true);

echo 
$arr["foo"]; // bar
echo $arr[12];    // 1
?>

A key may be either an integer or a string. If a key is the standard representation of an integer, it will be interpreted as such (i.e. "8" will be interpreted as 8, while "08" will be interpreted as "08"). Floats in key are truncated to integer. The indexed and associative array types are the same type in PHP, which can both contain integer and string indices.

A value can be any PHP type.

<?php
$arr 
= array("somearray" => array(=> 513 => 9"a" => 42));

echo 
$arr["somearray"][6];    // 5
echo $arr["somearray"][13];   // 9
echo $arr["somearray"]["a"];  // 42
?>

If a key is not specified for a value, the maximum of the integer indices is taken and the new key will be that value plus 1. If a key that already has an assigned value is specified, that value will be overwritten.

<?php
// This array is the same as ...
array(=> 433256"b" => 12);

// ...this array
array(=> 43=> 32=> 56"b" => 12);
?>
Warnung

Before PHP 4.3.0, appending to an array in which the current maximum key was negative would create a new key as described above. Since PHP 4.3.0, the new key will be 0.

Using TRUE as key will evaluate to integer 1 as a key. Using FALSE as key will evaluate to integer 0 as a key. Using NULL as a key will evaluate to the empty string. Using the empty string as a key will create (or overwrite) a key with the empty string and its value; it is not the same as using empty brackets.

Arrays and objects can not be used as keys. Doing so will result in a warning: Illegal offset type.

Creating/modifying with square bracket syntax

An existing array can be modified by explicitly setting values in it.

This is done by assigning values to the array, specifying the key in brackets. The key can also be omitted, resulting in an empty pair of brackets ([]).

$arr[key] = value;
$arr[] = value;
// key may be an integer or string
// value may be any value of any type

If $arr doesn't exist yet, it will be created, so this is also an alternative way to create an array. To change a certain value, assign a new value to that element using its key. To remove a key/value pair, call the unset() function on it.

<?php
$arr 
= array(=> 112 => 2);

$arr[] = 56;    // This is the same as $arr[13] = 56;
                // at this point of the script

$arr["x"] = 42// This adds a new element to
                // the array with key "x"
                
unset($arr[5]); // This removes the element from the array

unset($arr);    // This deletes the whole array
?>

Hinweis: As mentioned above, if no key is specified, the maximum of the existing integer indices is taken, and the new key will be that maximum value plus 1. If no integer indices exist yet, the key will be 0 (zero). If a key that already has a value is specified, that value will be overwritten.
Note that the maximum integer key used for this need not currently exist in the array. It need only have existed in the array at some time since the last time the array was re-indexed. The following example illustrates:

<?php
// Create a simple array.
$array = array(12345);
print_r($array);

// Now delete every item, but leave the array itself intact:
foreach ($array as $i => $value) {
    unset(
$array[$i]);
}
print_r($array);

// Append an item (note that the new key is 5, instead of 0).
$array[] = 6;
print_r($array);

// Re-index:
$array array_values($array);
$array[] = 7;
print_r($array);
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
)
Array
(
)
Array
(
    [5] => 6
)
Array
(
    [0] => 6
    [1] => 7
)

Useful functions

There are quite a few useful functions for working with arrays. See the array functions section.

Hinweis: The unset() function allows removing keys from an array. Be aware that the array will not be reindexed. If a true "remove and shift" behavior is desired, the array can be reindexed using the array_values() function.

<?php
$a 
= array(=> 'one'=> 'two'=> 'three');
unset(
$a[2]);
/* will produce an array that would have been defined as
   $a = array(1 => 'one', 3 => 'three');
   and NOT
   $a = array(1 => 'one', 2 =>'three');
*/

$b array_values($a);
// Now $b is array(0 => 'one', 1 =>'three')
?>

The foreach control structure exists specifically for arrays. It provides an easy way to traverse an array.

Array do's and don'ts

Why is $foo[bar] wrong?

Always use quotes around a string literal array index. For example, $foo['bar'] is correct, while $foo[bar] is not. But why? It is common to encounter this kind of syntax in old scripts:

<?php
$foo
[bar] = 'enemy';
echo 
$foo[bar];
// etc
?>

This is wrong, but it works. The reason is that this code has an undefined constant (bar) rather than a string ('bar' - notice the quotes). PHP may in future define constants which, unfortunately for such code, have the same name. It works because PHP automatically converts a bare string (an unquoted string which does not correspond to any known symbol) into a string which contains the bare string. For instance, if there is no defined constant named bar, then PHP will substitute in the string 'bar' and use that.

Hinweis: This does not mean to always quote the key. Do not quote keys which are constants or variables, as this will prevent PHP from interpreting them.

<?php
error_reporting
(E_ALL);
ini_set('display_errors'true);
ini_set('html_errors'false);
// Simple array:
$array = array(12);
$count count($array);
for (
$i 0$i $count$i++) {
    echo 
"\nChecking $i: \n";
    echo 
"Bad: " $array['$i'] . "\n";
    echo 
"Good: " $array[$i] . "\n";
    echo 
"Bad: {$array['$i']}\n";
    echo 
"Good: {$array[$i]}\n";
}
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

Checking 0: 
Notice: Undefined index:  $i in /path/to/script.html on line 9
Bad: 
Good: 1
Notice: Undefined index:  $i in /path/to/script.html on line 11
Bad: 
Good: 1

Checking 1: 
Notice: Undefined index:  $i in /path/to/script.html on line 9
Bad: 
Good: 2
Notice: Undefined index:  $i in /path/to/script.html on line 11
Bad: 
Good: 2

More examples to demonstrate this behaviour:

<?php
// Show all errors
error_reporting(E_ALL);

$arr = array('fruit' => 'apple''veggie' => 'carrot');

// Correct
print $arr['fruit'];  // apple
print $arr['veggie']; // carrot

// Incorrect.  This works but also throws a PHP error of level E_NOTICE because
// of an undefined constant named fruit
// 
// Notice: Use of undefined constant fruit - assumed 'fruit' in...
print $arr[fruit];    // apple

// This defines a constant to demonstrate what's going on.  The value 'veggie'
// is assigned to a constant named fruit.
define('fruit''veggie');

// Notice the difference now
print $arr['fruit'];  // apple
print $arr[fruit];    // carrot

// The following is okay, as it's inside a string. Constants are not looked for
// within strings, so no E_NOTICE occurs here
print "Hello $arr[fruit]";      // Hello apple

// With one exception: braces surrounding arrays within strings allows constants
// to be interpreted
print "Hello {$arr[fruit]}";    // Hello carrot
print "Hello {$arr['fruit']}";  // Hello apple

// This will not work, and will result in a parse error, such as:
// Parse error: parse error, expecting T_STRING' or T_VARIABLE' or T_NUM_STRING'
// This of course applies to using superglobals in strings as well
print "Hello $arr['fruit']";
print 
"Hello $_GET['foo']";

// Concatenation is another option
print "Hello " $arr['fruit']; // Hello apple
?>

When error_reporting is set to show E_NOTICE level errors (by setting it to E_ALL, for example), such uses will become immediately visible. By default, error_reporting is set not to show notices.

As stated in the syntax section, what's inside the square brackets ('[' and ']') must be an expression. This means that code like this works:

<?php
echo $arr[somefunc($bar)];
?>

This is an example of using a function return value as the array index. PHP also knows about constants:

<?php
$error_descriptions
[E_ERROR]   = "A fatal error has occured";
$error_descriptions[E_WARNING] = "PHP issued a warning";
$error_descriptions[E_NOTICE]  = "This is just an informal notice";
?>

Note that E_ERROR is also a valid identifier, just like bar in the first example. But the last example is in fact the same as writing:

<?php
$error_descriptions
[1] = "A fatal error has occured";
$error_descriptions[2] = "PHP issued a warning";
$error_descriptions[8] = "This is just an informal notice";
?>

because E_ERROR equals 1, etc.

So why is it bad then?

At some point in the future, the PHP team might want to add another constant or keyword, or a constant in other code may interfere. For example, it is already wrong to use the words empty and default this way, since they are reserved keywords.

Hinweis: To reiterate, inside a double-quoted string, it's valid to not surround array indexes with quotes so "$foo[bar]" is valid. See the above examples for details on why as well as the section on variable parsing in strings.

Converting to array

For any of the types: integer, float, string, boolean and resource, converting a value to an array results in an array with a single element with index zero and the value of the scalar which was converted. In other words, (array)$scalarValue is exactly the same as array($scalarValue).

If an object is converted to an array, the result is an array whose elements are the object's properties. The keys are the member variable names, with a few notable exceptions: private variables have the class name prepended to the variable name; protected variables have a '*' prepended to the variable name. These prepended values have null bytes on either side. This can result in some unexpected behaviour:

<?php

class {
    private 
$A// This will become '\0A\0A'
}

class 
extends {
    private 
$A// This will become '\0B\0A'
    
public $AA// This will become 'AA'
}

var_dump((array) new B());
?>

The above will appear to have two keys named 'AA', although one of them is actually named '\0A\0A'.

Converting NULL to an array results in an empty array.

Comparing

It is possible to compare arrays with the array_diff() function and with array operators.

Examples

The array type in PHP is very versatile. Here are some examples:

<?php
// this
$a = array( 'color' => 'red',
            
'taste' => 'sweet',
            
'shape' => 'round',
            
'name'  => 'apple',
                       
4        // key will be 0
          
);

// is completely equivalent with
$a['color'] = 'red';
$a['taste'] = 'sweet';
$a['shape'] = 'round';
$a['name']  = 'apple';
$a[]        = 4;        // key will be 0

$b[] = 'a';
$b[] = 'b';
$b[] = 'c';
// will result in the array array(0 => 'a' , 1 => 'b' , 2 => 'c'),
// or simply array('a', 'b', 'c')
?>

Beispiel #1 Using array()

<?php
// Array as (property-)map
$map = array( 'version'    => 4,
              
'OS'         => 'Linux',
              
'lang'       => 'english',
              
'short_tags' => true
            
);
            
// strictly numerical keys
$array = array( 7,
                
8,
                
0,
                
156,
                -
10
              
);
// this is the same as array(0 => 7, 1 => 8, ...)

$switching = array(         10// key = 0
                    
5    =>  6,
                    
3    =>  7
                    
'a'  =>  4,
                            
11// key = 6 (maximum of integer-indices was 5)
                    
'8'  =>  2// key = 8 (integer!)
                    
'02' => 77// key = '02'
                    
0    => 12  // the value 10 will be overwritten by 12
                  
);
                  
// empty array
$empty = array();         
?>

Beispiel #2 Collection

<?php
$colors 
= array('red''blue''green''yellow');

foreach (
$colors as $color) {
    echo 
"Do you like $color?\n";
}

?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

Do you like red?
Do you like blue?
Do you like green?
Do you like yellow?

Changing the values of the array directly is possible since PHP 5 by passing them by reference. Before that, a workaround is necessary:

Beispiel #3 Collection

<?php
// PHP 5
foreach ($colors as &$color) {
    
$color strtoupper($color);
}
unset(
$color); /* ensure that following writes to
$color will not modify the last array element */

// Workaround for older versions
foreach ($colors as $key => $color) {
    
$colors[$key] = strtoupper($color);
}

print_r($colors);
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

Array
(
    [0] => RED
    [1] => BLUE
    [2] => GREEN
    [3] => YELLOW
)

This example creates a one-based array.

Beispiel #4 One-based index

<?php
$firstquarter  
= array(=> 'January''February''March');
print_r($firstquarter);
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

Array 
(
    [1] => 'January'
    [2] => 'February'
    [3] => 'March'
)

Beispiel #5 Filling an array

<?php
// fill an array with all items from a directory
$handle opendir('.');
while (
false !== ($file readdir($handle))) {
    
$files[] = $file;
}
closedir($handle); 
?>

Arrays are ordered. The order can be changed using various sorting functions. See the array functions section for more information. The count() function can be used to count the number of items in an array.

Beispiel #6 Sorting an array

<?php
sort
($files);
print_r($files);
?>

Because the value of an array can be anything, it can also be another array. This enables the creation of recursive and multi-dimensional arrays.

Beispiel #7 Recursive and multi-dimensional arrays

<?php
$fruits 
= array ( "fruits"  => array ( "a" => "orange",
                                       
"b" => "banana",
                                       
"c" => "apple"
                                     
),
                  
"numbers" => array ( 1,
                                       
2,
                                       
3,
                                       
4,
                                       
5,
                                       
6
                                     
),
                  
"holes"   => array (      "first",
                                       
=> "second",
                                            
"third"
                                     
)
                );

// Some examples to address values in the array above 
echo $fruits["holes"][5];    // prints "second"
echo $fruits["fruits"]["a"]; // prints "orange"
unset($fruits["holes"][0]);  // remove "first"

// Create a new multi-dimensional array
$juices["apple"]["green"] = "good"
?>

Array assignment always involves value copying. It also means that the internal array pointer used by current() and similar functions is reset. Use the reference operator to copy an array by reference.

<?php
$arr1 
= array(23);
$arr2 $arr1;
$arr2[] = 4// $arr2 is changed,
             // $arr1 is still array(2, 3)
             
$arr3 = &$arr1;
$arr3[] = 4// now $arr1 and $arr3 are the same
?>


Objects

Object Initialization

To create a new object, use the new statement to instantiate a class:

<?php
class foo
{
    function 
do_foo()
    {
        echo 
"Doing foo."
    }
}

$bar = new foo;
$bar->do_foo();
?>

For a full discussion, see the Classes and Objects chapter.

Converting to object

If an object is converted to an object, it is not modified. If a value of any other type is converted to an object, a new instance of the stdClass built-in class is created. If the value was NULL, the new instance will be empty. Arrays convert to an object with properties named by keys, and corresponding values. For any other value, a member variable named scalar will contain the value.

<?php
$obj 
= (object) 'ciao';
echo 
$obj->scalar;  // outputs 'ciao'
?>


Ressourcen

Eine resource ist eine spezielle Variable, die eine Referenz zu einer externen Ressource darstellt. Ressourcen werden mit Hilfe spezieller Funktionen erzeugt und genutzt. Im Anhang finden Sie eine Liste all dieser Funktionen und der zugehörigen resource-Typen.

Hinweis: Der resource-Typ wunde in PHP 4 eingeführt.

Siehe auch get_resource_type().

Konvertierung von Resosurcen.

Da resource-Variablen spezielle Referenzen auf geöffnete Dateien, Datenbankverbindungen, Grafikbereichen usw. enthalten macht die Konvertierung von resource keinen Sinn.

Resourcen freigeben

Dank der mit der Zend Engine von PHP 4 eingeführten Referenzzähler werden Ressourcen, die von keiner Variablen mehr referenziert werden, automatisch erkannt und vom Garbage Collector freigegeben. Aus diesem Grund ist es selten nötig Speicher von Hand freizugeben.

Hinweis: Persistente Datenbankverbindungen sind eine Ausnahme von dieser Regel, sie werden nicht vom Garbage Collector entfernt. Mehr Informationen finden sie im Abschnitt Persistente Verbindungen.



NULL

Der spezielle Wert NULL repräsentiert eine Variable ohne Wert. NULL ist der einzig mögliche Wert des Typs NULL.

Hinweis: Der null Typ wurde in PHP eingeführt.

Eine Variable gilt als vom Typ null wenn:

  • ihr die Konstante NULL zugewiesen wurde.

  • ihr noch kein Wert zugewiesen wurde.

  • sie mit unset() gelöscht wurde.

Syntax

Es gibt nur einen Wert vom Typ null: das Schlüsselwort NULL (Groß- und Kleinschreibung ist dabei nicht wichtig).

<?php
$var 
NULL;       
?>

Siehe auch die Funktionen is_null() und unset().

Umwandlung auf NULL

Die Umwandlung einer Variable auf den Typ null entfernt die Variable und löscht ihren Inhalt.



Pseudo-types and variables used in this documentation

mixed

mixed indicates that a parameter may accept multiple (but not necessarily all) types.

gettype() for example will accept all PHP types, while str_replace() will accept strings and arrays.

number

number indicates that a parameter can be either integer or float.

callback

Some functions like call_user_func() or usort() accept user-defined callback functions as a parameter. Callback functions can not only be simple functions, but also object methods, including static class methods.

A PHP function is passed by its name as a string. Any built-in or user-defined function can be used, except language constructs such as: array(), echo(), empty(), eval(), exit(), isset(), list(), print() or unset().

A method of an instantiated object is passed as an array containing an object at index 0 and the method name at index 1.

Static class methods can also be passed without instantiating an object of that class by passing the class name instead of an object at index 0.

Apart from common user-defined function, create_function() can also be used to create an anonymous callback function.

Beispiel #1 Callback function examples

<?php 

// An example callback function
function my_callback_function() {
    echo 
'hello world!';
}

// An example callback method
class MyClass {
    static function 
myCallbackMethod() {
        echo 
'Hello World!';
    }
}

// Type 1: Simple callback
call_user_func('my_callback_function'); 

// Type 2: Static class method call
call_user_func(array('MyClass''myCallbackMethod')); 

// Type 3: Object method call
$obj = new MyClass();
call_user_func(array($obj'myCallbackMethod'));

// Type 4: Static class method call (As of PHP 5.2.3)
call_user_func('MyClass::myCallbackMethod');

// Type 5: Relative static class method call (As of PHP 5.3.0)
class {
    public static function 
who() {
        echo 
"A\n";
    }
}

class 
extends {
    public static function 
who() {
        echo 
"B\n";
    }
}

call_user_func(array('B''parent::who')); // A
?>

Hinweis: In PHP4, it was necessary to use a reference to create a callback that points to the actual object, and not a copy of it. For more details, see References Explained.

void

void as a return type means that the return value is useless. void in a parameter list means that the function doesn't accept any parameters.

...

$... in function prototypes means and so on. This variable name is used when a function can take an endless number of arguments.



Type Juggling

PHP does not require (or support) explicit type definition in variable declaration; a variable's type is determined by the context in which the variable is used. That is to say, if a string value is assigned to variable $var, $var becomes a string. If an integer value is then assigned to $var, it becomes an integer.

An example of PHP's automatic type conversion is the addition operator '+'. If either operand is a float, then both operands are evaluated as floats, and the result will be a float. Otherwise, the operands will be interpreted as integers, and the result will also be an integer. Note that this does not change the types of the operands themselves; the only change is in how the operands are evaluated and what the type of the expression itself is.

<?php
$foo 
"0";  // $foo is string (ASCII 48)
$foo += 2;   // $foo is now an integer (2)
$foo $foo 1.3;  // $foo is now a float (3.3)
$foo "10 Little Piggies"// $foo is integer (15)
$foo "10 Small Pigs";     // $foo is integer (15)
?>

If the last two examples above seem odd, see String conversion to numbers.

To force a variable to be evaluated as a certain type, see the section on Type casting. To change the type of a variable, see the settype() function.

To test any of the examples in this section, use the var_dump() function.

Hinweis: The behaviour of an automatic conversion to array is currently undefined.
Also, because PHP supports indexing into strings via offsets using the same syntax as array indexing, the following example holds true for all PHP versions:

<?php
$a    
'car'// $a is a string
$a[0] = 'b';   // $a is still a string
echo $a;       // bar
?>

See the section titled String access by character for more information.

Type Casting

Type casting in PHP works much as it does in C: the name of the desired type is written in parentheses before the variable which is to be cast.

<?php
$foo 
10;   // $foo is an integer
$bar = (boolean) $foo;   // $bar is a boolean
?>

The casts allowed are:

  • (int), (integer) - cast to integer
  • (bool), (boolean) - cast to boolean
  • (float), (double), (real) - cast to float
  • (string) - cast to string
  • (binary) - cast to binary string (PHP 6)
  • (array) - cast to array
  • (object) - cast to object
  • (unset) - cast to NULL (PHP 5)

(binary) casting and b prefix forward support was added in PHP 5.2.1

Note that tabs and spaces are allowed inside the parentheses, so the following are functionally equivalent:

<?php
$foo 
= (int) $bar;
$foo = ( int ) $bar;
?>

Casting literal strings and variables to binary strings:

<?php
$binary 
= (binary)$string;
$binary b"binary string";
?>

Hinweis: Instead of casting a variable to a string, it is also possible to enclose the variable in double quotes.

<?php
$foo 
10;            // $foo is an integer
$str "$foo";        // $str is a string
$fst = (string) $foo// $fst is also a string

// This prints out that "they are the same"
if ($fst === $str) {
    echo 
"they are the same";
}
?>

It may not be obvious exactly what will happen when casting between certain types. For more information, see these sections:




Variablen

Inhaltsverzeichnis


Grundlegendes

Variablen werden in PHP dargestellt durch ein Dollar-Zeichen ($) gefolgt vom Namen der Variablen. Bei Variablen-Namen wird zwischen Groß- und Kleinschreibung unterschieden (case-sensitive).

Variablen-Namen werden in PHP nach den gleichen Regeln wie andere Bezeichner erstellt. Ein gültiger Variablen-Name beginnt mit einem Buchstaben oder einem Unterstrich ("_"), gefolgt von einer beliebigen Anzahl von Buchstaben, Zahlen oder Unterstrichen. Als regulärer Ausdruck (regular expression) würde das wie folgt ausgedrückt: '[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*'.

Hinweis: Unserem Zweck entspricht also ein Buchstabe von a bis z bzw. A bis Z oder einem ASCII-Zeichen von 127 bis 255 (0x7f bis 0xff).

Hinweis: $this ist eine spezielle Variable der kein Wert zugewiesen werden kann.

Tipp

Siehe auch Userland Naming Guide.

Information zu Funktionen im Zusammenhang mit Variablen finden Sie im Abschnitt Funktionen zur Behandlung von Variablen.

<?php
$var 
"Du";
$vaR "und";
$Var "ich";
$vAr "wir lernen PHP"
echo "$var $vaR $Var$vAr"// gibt "Du und ich, wir lernen PHP" aus

$4site  'nicht jetzt';     // ungültig, da Anfang eine Zahl
$_4site 'nicht jetzt';     // gültig, da Unterstrich am Anfang
$täbyte 'irgendwas';       // gültig, da 'ä' dem (Erweiterten) ASCII-Wert 228 entspricht
?>

Variablen werden durch ihren Wert bestimmt. Das heisst, wenn Sie einer Variablen einen Ausdruck zuweisen, wird der gesamte Inhalt des Originalausdrucks in die Zielvariable kopiert. Die Folge ist, dass eine Variable, die ihren Inhalt von einer anderen Variablen erhalten hat, ihren Inhalt behält, auch wenn Sie danach den Inhalt der anderen (Quell- / Ursprungs-)Variablen ändern. Die Inhalte der Ziel- und Quellvariablen sind also insoweit unabhängig voneinander. Für weitere Informationen lesen Sie bitte das Kapitel unter Expressions / Ausdrücke.

PHP bietet eine andere Möglichkeit der Wertzuweisung bei Variablen: Zuweisung durch Referenzierung. Das bedeutet, dass der Wert der neuen Variablen eine Referenz zur Ursprungs-Variablen darstellt (mit anderen Worten: Der Wert ist ein Alias bzw. Zeiger auf den Inhalt der Ursprungsvariablen). Beide Variablen zeigen also auf die selbe(n) Speicherstelle(n). Änderungen der neuen Variablen ändern auch deren Ursprungs-Variable und umgekehrt.

Für die Zuweisung per Referenz müssen Sie lediglich ein & der (Ausgangs-, Quell-) Variablen voranstellen, die sie einer anderen Variablen zuweisen wollen. Der folgende Skript- Ausschnitt wird zweimal 'Mein Name ist Bob' ausgeben:

<?php
$foo 
'Bob';             // 'Bob' der Variablen $foo zuweisen.
$bar = &$foo;             // Zeiger auf $foo in $bar erzeugen.
$bar "Ich hei&szlig;e $bar";  // $bar verändern...
echo $bar;
echo 
$foo;                // $foo wurde dadurch ebenfalls verändert.
?>

Zu beachten ist, dass nur Variablenbezeichner referenziert werden können.

<?php
$foo 
25;
$bar = &$foo;     // Gültige Zuweisung.
$bar = &(24 7); // Ungültig, da kein Variablenbezeichner
                  // zugewiesen wird.
function test() {
    return 
25;
}

$bar = &test();   // Ungültig.
?>

Es ist in PHP nicht zwingend notwendig Variablen zu initialisieren, es wird aber trotzdem empfohlen. Nicht initialisierte Variablen haben einen Vorgabewert der vom Typ abhängt - FALSE Null, leerer String oder leeres Array.

Beispiel #1 Vorgabewerte uninitialisierter Variablen

<?php
echo ($unset_bool "true" "false"); // false
$unset_int += 25// 0 + 25 => 25
echo $unset_string "abc"// "" . "abc" => "abc"
$unset_array[3] = "def"// array() + array(3 => "def") => array(3 => "def")
?>

Es ist problematisch sich auf den Vorgabewert einer nicht initialisierten Variable zu verlassen wenn Sie Dateien inkludieren die die gleichen Variablennamen benutzen. Wenn register_globals aktiviert ist führt dies zu einem extremen Sicherheitsproblem. Bei Zugriffen auf nicht initialisierte Variablen wird ein Fehler der Stufe E_NOTICE ausgegeben, dies trifft allerdings nicht auf das Anfügen von Elementen an nicht initialisierte Arrays zu. Das isset() Sprachkonstrukt kann genutzt werden um zu prüfen ob eine Variable bereits initialisiert wurde.



Vordefinierte Variablen

PHP bietet jedem ausgeführtem Skript eine Vielzahl von vordefinierten Variablen an. Viele dieser Variablen können jedoch nicht vollständig erläutert werden, da sie abhängig sind vom Web-Server, der Version und dem Setup des Web- Servers sowie weiteren Faktoren. Einige dieser Variablen stehen nicht zur Verfügung, wenn PHP-Skripte per Kommando-Zeilen-Aufruf ausgeführt werden. Für eine Liste dieser Variablen lesen Sie bitte den Abschnitt Vordefinierte Variablen.

Warnung

Ab PHP 4.2.0 ist der standardmäßige Wert für die PHP-Anweisung register_globals off. Dies ist eine wesentliche Änderung in PHP. Die Anweisung register_globals off beeinflusst den Satz von vordefinierten Variablen, die im globalen Bereich verfügbar sind. Um zum Beispiel DOCUMENT_ROOT zu bekommen, müssen Sie $_SERVER['DOCUMENT_ROOT'] statt $DOCUMENT_ROOT verwenden oder um $id von der URL http://www.example.com/test.php?id=3 zu bekommen $_GET['id'] statt $id oder $_ENV['HOME'] statt $HOME.

Für diese Änderung betreffende Informationen lesen Sie bitte den Konfigurations-Eintrag für register_globals, das Sicherheitskapitel über die Verwendung von Register Globals und außerdem die PHP » 4.1.0 und » 4.2.0 Release Announcements.

Die reservierten vordefinierten Variablen, wie die Superglobalen Arrays, sollten bevorzugt verwendet werden.

Ab Version 4.1.0 stehen in PHP eine zusätzliche Reihe vordefinierter Arrays zur Verfügung, die Variablen vom Webserver (gegebenenfalls), von der Umgebung und von Benutzereingaben enthalten. Diese neuen Arrays sind insofern etwas sehr Spezielles, als sie automatisch global sind -- d.h., sie stehen automatisch in jedem Bereich zur Verfügung. Deshalb sind sie auch bekannt als 'Superglobale'. (Es gibt in PHP keinen Mechanismus für benutzerdefinierte Superglobale.) Die Superglobale werden nachfolgend aufgelistet, aber für eine Liste ihres Inhalts und die weitere Diskussion vordefinierter Variablen und ihres Wesens lesen Sie bitte den Abschnitt Reservierte vordefinierte Variablen. Außerdem werden Sie feststellen, dass die alten vordefinierten Variablen ($HTTP_*_VARS) noch existieren. Seit PHP 5.0.0 können Sie die Registrierung der langen von PHP vordefinierten Arrays mit der Konfigurationsoption register_long_arrays abschalten.

Hinweis: Variable Variablen
Superglobale können innerhalb von Funktionen und Methoden nicht als Variable Variablen verwendet werden.

Hinweis: Obwohl Superglobale und die HTTP_*_VARS zur gleichen Zeit existieren können sind sie nicht identisch. Änderungen dieser Variablen haben keinen Einfluss auf die jeweils anderen.

Falls bestimmte Variablen nicht unter variables_order angegeben sind, dann bleiben auch ihre entsprechenden vordefinierten Arrays leer.



Geltungsbereich von Variablen

Der Geltungsbereich einer Variablen ergibt sich aus dem Zusammenhang, in dem sie definiert wurde. Meistens besteht dieser aus einem einzigen Bereich. Dieser beinhaltet auch den Bereich für Dateien, die per "include"- oder "require"-Anweisung eingebunden wurden, z.B.:

<?php
$a 
1;
include 
"b.inc";
?>

Die Variable $a ist auch in der eingebundenen Datei b.inc verfügbar. In benutzerdefinierten Funktionen wird ein auf die Funktion beschränkter Geltungsbereich eingeführt. Jede in einer Funktion benutzte Variable ist zunächst auf den lokalen Bereich der Funktion beschränkt, z.B.:

<?php
$a 
1// globaler Bereich

function test () { 
    echo 
$a// Referenz auf einen lokalen Variablen-Bereich


test ();
?>

Dieses Skript erzeugt keine Bildschirm-Ausgabe, da sich die Echo- Anweisung auf eine lokale Variable namens $a bezieht und dieser kein Wert im lokalen Bezug zugewiesen worden ist. Dies ist ein kleiner Unterschied zu C, wo globale Variablen auch in Funktionen vorhanden sind, es sei denn, sie werden durch eine funktionsinterne Definition überschrieben. Das kann zu Problemen führen, denn in PHP müssen global geltende Variablen innerhalb von Funktionen als solche definiert werden.

Das global Schlüsselwort

Zunächst ein Beispiel für die Verwendung von global:

Beispiel #1 Die Verwendung von global

<?php
$a 
1;
$b 2;

function 
Summe()
{
    global 
$a$b;

    
$b $a $b;


Summe();
echo 
$b;
?>

Das obige Skript gibt "3" aus. Durch das Deklararieren der Variablen $a und $binnerhalb der Funktion als global, weisen alle Referenzen zu beiden Variablen auf die nun globalen Werte. Es gibt keine Beschränkungen bei der Anzahl an globalen Variablen, die durch eine Funktion verändert werden können.

Eine weitere Möglichkeit besteht in der Verwendung des speziellen $GLOBALS PHP-Array. Das obige Beispiel kann damit auch so geschrieben werden:

Beispiel #2 Die Verwendung von $GLOBALS statt global

<?php
$a 
1;
$b 2;

function 
Summe()
{
    
$GLOBALS["b"] = $GLOBALS["a"] + $GLOBALS["b"];


Summe();
echo 
$b;
?>

Das $GLOBALS-Array ist ein assoziatives Array mit dem Bezeichner der globalen Variablen als Schlüssel und dem Inhalt dieser Variablen als Wert des Array-Elements. Beachten Sie, dass $GLOBALS in jedem Bereich existiert, weil $GLOBALS eine Superglobale ist. Hier ist ein Beispiel, das die Stärke von Superglobalen demonstriert:

Beispiel #3 Beispiel zur Demonstration von Superglobalen und Bereich

<?php
function test_global()
{
    
// Die meisten vordefinierten Variablen sind nicht "super" und
    // benötigen 'global', um im lokalen Bereich von Funktionen zur
    // Verfügung zu stehen.
    
global $HTTP_POST_VARS;

    echo 
$HTTP_POST_VARS['name'];

    
// Superglobale stehen in jedem Bereich zur Verfügung und
    // benötigen kein 'global'. Superglobale stehen seit PHP 4.1.0
    // zur Verfügung und HTTP_POST_VARS gilt nun als veraltet
    
echo $_POST['name'];
}
?>

Die Verwendung von statischen Variablen

Ein weiterer wichtiger Anwendungszweck von Variablen-Bereichen ist die static-Variable. Eine statische Variable existiert nur in einem lokalen Funktions-Bereich, der Wert geht beim Verlassen dieses Bereichs aber nicht verloren. Schauen Sie das folgende Beispiel an:

Beispiel #4 Beispiel, das die Notwendigkeit von statischen Variablen demonstriert

<?php
function test ()
{
    
$a 0;
    echo 
$a;
    
$a++;
}
?>

Diese Funktion ist sinnlos, da sie bei jedem Aufruf $a auf 0 setzt und "0" ausgibt. Die Anweisung $a++, welche den Wert erhöht, macht keinen Sinn, da der Wert von $a beim Verlassen der Funktion verloren geht. Um eine sinnvolle Zählfunktion zu implementieren, die ihren aktuell gesetzten Wert nicht vergisst, müssen Sie die Variable $aals "static" deklarieren:

Beispiel #5 Beispiel zur Verwendung statischer Variablen

<?php
function Test()
{
    static 
$a 0;
    echo 
$a;
    
$a++;
}
?>

Jetzt wird bei jedem Aufruf der Test()-Funktion der aktuelle Wert von $a ausgegeben und dann um 1 erhöht.

Static-Variablen ermöglichen auch einen Weg zum Umgang mit rekursiven Funktionen. Das sind Funktionen, die sich selbst aufrufen. Hierbei besteht die Gefahr, so genannte Endlos- Schleifen zu programmieren. Sie müssen also einen Weg vorsehen, diese Rekursion zu beenden. Die folgende einfache Funktion zählt rekursiv bis 10. Die statische Variable $zaehler wird benutzt, um die Rekursion zu beenden:

Beispiel #6 Statische Variablen in rekursiven Funktionen

<?php
function Test()
{
    static 
$zaehler 0;

    
$zaehler++;
    echo 
$zaehler;
    if (
$zaehler 10) {
        
Test ();
    }
    
$zaehler--;
}
?>

Hinweis: Statische Variablen werden wie in oben stehenden Beispielen deklariert. Das Zuweisen eines Wertes, welcher das Ergebnis eines Ausdrucks ist, wird mit einem parse error quittiert.

Beispiel #7 Statische Variablen deklarieren

<?php
function foo(){
    static 
$int 0;          // korrekt
    
static $int 1+2;        // falsch  (da ein Ausdruck vorliegt)
    
static $int sqrt(121);  // falsch  (ebenfalls ein Ausdruck)

    
$int++;
    echo 
$int;
}
?>


Referenzen bei globalen und statischen Variablen

Die Zend Engine 1, die PHP 4 zugrunde liegt, führt die static- und global-Wandler für Variablen in Bezug auf Referenzen aus. Zum Beispiel erzeugt eine echte globale Variable, die mit der Anweisung global in den Funktionsbereich importiert wurde, tatsächlich eine Referenz zur globalen Variable. Das kann zu einem unerwarteten Verhalten führen, auf das im folgenden Beispiel eingegangen wird:

<?php
function test_global_ref() {
    global 
$obj;
    
$obj = &new stdclass;
}

function 
test_global_noref() {
    global 
$obj;
    
$obj = new stdclass;
}

test_global_ref();
var_dump($obj);
test_global_noref();
var_dump($obj);
?>

Die Ausführung dieses Beispiels erzeugt die folgende Ausgabe:


NULL
object(stdClass)(0) {
}

Ein ähnliches Verhalten gilt auch für die Anweisung static. Referenzen werden nicht statisch gespeichert:

<?php
function &get_instance_ref() {
    static 
$obj;

    echo 
"Statisches Objekt: ";
    
var_dump($obj);
   if (!isset(
$obj)) {
        
// Der statischen Variablen eine Referenz zuweisen
        
$obj = &new stdclass;
    }
    
$obj->eigenschaft++;
    return 
$obj;
}

function &
get_instance_noref() {
    static 
$obj;

    echo 
"Statisches Objekt: ";
    
var_dump($obj);
    if (!isset(
$obj)) {
        
// Der statischen Variablen ein Objekt zuweisen
        
$obj = new stdclass;
    }
    
$obj->eigenschaft++;
    return 
$obj;
}

$obj1 get_instance_ref();
$immer_noch_obj1 get_instance_ref();
echo 
"\n";
$obj2 get_instance_noref();
$immer_noch_obj2 get_instance_noref();
?>

Die Ausführung dieses Beispiels erzeugt die folgende Ausgabe:


Statisches Objekt: NULL
Statisches Objekt: NULL

Statisches Objekt: NULL
Statisches Objekt: object(stdClass)(1) {
["eigenschaft"]=>
int(1)
}

Dieses Beispiel demonstriert, dass die Referenz, die einer statischen Variablen zugewiesen wird, beim zweiten Aufruf der Funktion &get_instance_ref() vergessen ist.



Variable Variablen

Manchmal ist es komfortabel, variable Variablen-Bezeichner zu benutzen. Das bedeutet, einen Variablen-Namen zu setzen und dynamisch zu gebrauchen. Eine normale Variable wird wie folgt gebildet:

<?php
$a 
"Hallo";
?>

Eine variable Variable nimmt den Wert einer Variablen und behandelt ihn als Bezeichner der Variablen. Im obigen Beispiel kann Hallo als Variablen-Name gebraucht werden, indem man zwei $-Zeichen benutzt, also schreibt:

<?php
$$a "Welt";
?>

Nun existieren in der PHP-Symbol-Struktur zwei definierte und gespeicherte Variablen: $a mit dem Inhalt "Hallo" und $Hallo mit dem Inhalt "Welt". Deshalb wird die Anweisung

<?php
echo "$a ${$a}";
?>

zur genau gleichen Ausgabe führen wie:

<?php
echo "$a $Hallo";
?>

also zu: Hallo Welt.

Wenn Sie variable Variablen mit Arrays verwenden, müssen Sie eine Doppeldeutigkeit beachten. Wenn Sie nämlich $$a[1] schreiben, dann muss der Parser wissen, ob Sie $a[1] als Variable oder $$a als Variable und dann [1] als Index dieser Variablen verwenden wollen bzw. gemeint haben. Die Syntax zur Lösung dieser Doppeldeutigkeit: Verwenden Sie im ersten Fall ${$a[1]} und im zweiten Fall ${$a}[1].

Warnung

Bitte beachten Sie, dass variable Variablen nicht bei Superglobalen Arrays verwendet werden können. Die Variable $this ist also eine spezielle Variabele die nicht dynamisch referenziert werden kann.



Variablen aus externen Quellen

HTML-Formulare (GET and POST)

Sobald ein Formular an ein PHP-Skript übergeben wird, werden die Informationen dieses Formulars dem Skript automatisch verfügbar gemacht. Es gibt viele Möglichkeiten, auf diese Informationen zuzugreifen, zum Beispiel:

Beispiel #1 Ein einfaches HTML-Formular

<form action="foo.php" method="post">
    Name:  <input type="text" name="username" /><br />
    Email: <input type="text" name="email" /><br />
    <input type="submit" name="submit" value="Und ab!" />
</form>

Abhängig von Ihrem speziellen Setup und Ihren persönlichen Vorlieben gibt es viele Möglichkeiten, auf die Daten von Ihren HTML-Formularen zuzugreifen. Hier einige Beispiele:

Beispiel #2 Zugriff auf die Daten von einem einfachen POST HTML-Formular

<?php
// Seit PHP 4.1.0 verfügbar

   echo $_POST['benutzername'];
   echo $_REQUEST['benutzername'];

   import_request_variables('p', 'p_');
   echo $p_benutzername;

// Ab PHP 6.0.0 nicht mehr verfügbar. Ab PHP 5.0.0 können diese langen
// vordefinierten Variablen mit der Anweisung register_long_arrays
// deaktiviert werden.

   echo $HTTP_POST_VARS['benutzername'];

// Verfügbar, falls die PHP-Anweisung register_globals = on. Ab
// PHP 4.2.0 ist der standardmäßige Wert von register_globals = off.
// Es ist nicht empfehlenswert, diese Methode zu verwenden, bzw. sich
// darauf zu verlassen.

   echo $benutzername;
?>

Die Verwendung eines GET Formulars ist, davon abgesehen, dass Sie stattdessen die entsprechende vordefinierte GET-Variable erhalten, ähnlich. Außerdem wird GET auch für den QUERY_STRING (die Information nach dem '?' in einer URL) verwendet. So enthält zum Beispiel http://www.example.com/test.php?id=3 GET-Daten, auf die mit $_GET['id'] zugegriffen werden kann. Siehe auch $_REQUEST und import_request_variables().

Hinweis: Superglobale Arrays wie $_POST und $_GET stehen seit PHP 4.1.0 zur Verfügung.

Wie gezeigt, war register_globals vor PHP 4.2.0 standardmäßig on. Die PHP-Gemeinschaft ermuntert alle, sich nicht auf diese Anweisung zu stützen, weil es vorzuziehen ist, davon auszugehen, dass sie off ist und entsprechend zu programmieren.

Hinweis: Die Konfigurationseinstellung zu magic_quotes_gpc betrifft Get-, Post- und Cookie-Werte. Ist diese Einstellung aktiv, wird der Wert (It's "PHP!") automatisch zu (It\'s \"PHP!\"). Escaping ist notwendig, wenn Sie ihre Daten in eine Datenbank einfügen wollen. Siehe auch addslashes(), stripslashes() und magic_quotes_sybase.

Im Zusammenhang mit Formular-Variablen versteht PHP auch Arrays (siehe auch die verwandte Faq). Sie können z.B. die betreffenden Variablen gruppieren oder dieses Leistungsmerkmal nutzen, um Werte aus Mehrfach-Auswahl-Bereichen zu erhalten. Schicken wir zum Beispiel ein Formular an sich selbst und lassen nach dem Abschicken die Daten anzeigen:

Beispiel #3 Komplexere Formular-Variablen

<?php
if ($_POST) {
    echo 
'<pre>';
    echo 
htmlspecialchars(print_r($_POSTtrue));
    echo 
'</pre>';
}
?>
<form action="" method="post">
    Name:  <input type="text" name="personal[name]" /><br />
    Email: <input type="text" name="personal[email]" /><br />
    Bier: <br />
    <select multiple name="bier[]">
        <option value="warthog">Warthog</option>
        <option value="guinness">Guinness</option>
        <option value="stuttgarter">Stuttgarter Schwabenbräu</option>
    </select><br />
    <input type="submit" name="submit" value="Und ab!" />
</form>

IMAGE SUBMIT Variablen-Bezeichner

Zur Übertragung eines Formulars kann auch ein Bild (Image) statt eines Übertragungs-Schalters (Submit-Button) benutzt werden, dessen Tag wie folgt aussieht:

<input type="image" src="image.gif" name="sub" />

Klickt der Benutzer irgendwo auf das Bild, wird das entsprechende Formular an den Web-Server übertragen. Hierbei sind zwei zusätzliche Variablen vorhanden, sub_x und sub_y. Diese enthalten die Koordinaten des Klick-Punktes innerhalb des Bildes. Die Erfahreneren werden sagen, dass die Variablen, die vom Browser gesendet werden einen Punkt enthalten statt eines Unterstrichs. Dieser Punkt wird von PHP automatisch in einen Unterstrich verwandelt.

HTTP-Cookies

PHP unterstützt HTTP-Cookies, wie sie in » Netscape's Spec definiert sind. Cookies ermöglichen die Daten-Speicherung innerhalb der jeweiligen Browser-Umgebung zur Weiterleitung oder wiederholten Identifikation von Benutzern. Sie können Cookies erzeugen, indem Sie die Funktion setcookie() benutzen. Cookies sind Teil des HTTP-Headers, deshalb muss die setcookie-Funktion aufgerufen werden, bevor irgendeine Ausgabe an den Browser gesendet wird. Dabei handelt es sich um die gleiche Einschränkung, die auch für die header()-Funktion gilt. Cookie-Daten stehen dann sowohl in den entsprechenden Cookie-Daten-Arrays, wie zum Beispiel $_COOKIE, $HTTP_COOKIE_VARS als auch in $_REQUEST zur Verfügung. Für weitere Details und Beispiele lesen Sie bitte die setcookie()-Seite des Handbuchs.

Wenn Sie einer einzelnen Cookie-Variable mehrere Werte zuweisen wollen, müssen Sie diese als Array übertragen. Zum Beispiel:

<?php
setcookie
("MeinCookie[foo]""Ich teste 1"time()+3600);
setcookie("MeinCookie[bar]""Ich teste 2"time()+3600);
?>

Das erzeugt zwei einzelne Cookies obwohl MeinCookie in Ihrem Skript nun ein einziges Array ist. Wenn Sie nur ein Cookie mit mehreren Werten setzen wollen, sollten Sie zuerst serialize() oder explode() auf das Array anwenden.

Bedenken Sie, dass ein Cookie ein vorhergehendes Cookie gleichen Namens überschreibt, es sei denn, der Pfad oder die Domain ist anders. Für eine Warenkorb-Anwendung können Sie deshalb z.B. einen Zähler bilden und diesen weiterleiten:

Beispiel #4 Ein setcookie()-Beispiel

<?php
if (isset($_COOKIE['zaehler'])) {
    
$zaehler $_COOKIE['zaehler'] + 1;
} else {
    
$zaehler 1;
}
setcookie("zaehler"$zaehlertime()+3600);
setcookie("Cart[$zaehler]"$itemtime()+3600);
?>

Punkte in eingelesenen Variablen-Bezeichnern

Normalerweise verändert PHP die Variablen-Bezeichner nicht, wenn sie einem Skript übergeben werden. Es sollte aber beachtet werden, dass der Punkt (".") kein gültiger Bestandteil eines Variablen-Bezeichners ist. Deshalb achten Sie auf folgendes:

<?php
$varname
.ext;  /* ungültiger Variablen-Bezeichner */
?>

Der PHP-Parser sieht eine Variable namens $varname, gefolgt von einem Zeichenketten-Verbindungs-Operator, dieser wiederrum gefolgt von der offenen Zeichenkette 'ext' (also nicht eingegrenzt durch '"' und auch keinem Schlüssel oder reserviertem Bezeichner entsprechend). Das kann natürlich nicht zum gewünschten Ergebnis führen.

Deshalb ist es wichtig zu wissen, dass PHP in den ihm übergebenen Variablen alle Punkte (.) automatisch durch einen Unterstrich (_) ersetzt.

Bestimmung des Variablen-Typs

Da PHP den Typ der Variablen bestimmt und (im Allgemeinen) selbst eine entsprechende Umformung vornimmt, ist es nicht immer klar, welchen Typ eine Variable gerade hat. PHP beinhaltet einige Funktionen, die dies herausfinden, wie zum Beispiel: gettype(), is_array(), is_float(), is_int(), is_object() und is_string(). Lesen Sie bitte auch das Kapitel über Typen.




Konstanten

Inhaltsverzeichnis

Eine Konstante ist ein Bezeichner (Name) für eine einfache Variable. Wie der Name bereits nahelegt, kann der Wert einer Konstanten zur Laufzeit des Skripts nicht verändert werden (ausgenommen die Magischen Konstanten, die aber keine wirklichen Konstanten sind.) Eine Konstante unterscheidet standardmäßig zwischen Groß- und Kleinschreinbung (case-sensitive). Nach gängiger Konvention werden Konstanten immer in Großbuchstaben geschrieben.

Der Name einer Konstanten folgt den gleichen Regeln wie alle anderen Bezeichner in PHP. Ein gültiger Name beginnt mit einem Buchstaben oder einem Unterstrich, gefolgt von beliebig vielen Buchstaben, Ziffern oder Understrichen. Als regulärer Ausdruck könnte das so beschrieben werden: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*

Tipp

Siehe auch Userland Naming Guide.

Beispiel #1 Gültige und ungültige Namen für Konstanten

<?php

// Gueltige Namen fuer Konstanten
define("FOO",     "irgendwas");
define("FOO2",    "etwas anderes");
define("FOO_BAR""irgendwas ganz anderes");

// Ungueltige Namen fuer Konstanten
define("2FOO",    "irgendwas");

// Folgendes ist korrekt, sollte aber vermieden werden:
// PHP koennte eines Tages eine Magische Konstante unterstuetzen
// die Ihr Skript nicht mehr wie gewuenscht funktionieren laesst
define("__FOO__""irgendwas");

?>

Hinweis: Für unsere Zwecke ist ein Buchstabe a-z, A-Z und die ASCII-Zeichen von 127 bis 255 (0x7f-0xff).

Wie bei superglobals ist der Gültigkeitsbereich einer Konstanten global. Unabhängig vom Gültigkeitsbereich können Sie in Ihrem Skript überall auf eine Konstante zugreifen. Für mehr Information zum Gültigkeitsbereich lesen Sie bitte den Abschnitt über den Geltungsbereich von Variablen.


Syntax

Sie können eine Konstante definieren, indem Sie entweder die define()-Funktion oder ab PHP 5.3.0 das Schlüsselwort const außerhalb einer Klassendefinition verwenden. Einmal definiert, kann eine Konstane weder verändert noch gelöscht werden.

Konstanten können nur skalare Daten (boolean, integer, float und string) enthalten. Es ist möglich, Konstanten vom Typ resource zu definieren, dies sollte allerdings vermieden werden, da es zu unerwarteten Ergebnissen führen kann.

Den Wert einer Konstanten erhalten Sie durch die einfache Angabe ihres Namens. Im Gegensatz zu Variablen sollten Sie einer Konstanten kein $ voranstellen. Ebenso können Sie die Funktion constant() benutzen, um den Wert einer Konstanten auszulesen, wenn Sie den Namen der Konstanten dynamisch erhalten wollen. Benutzen Sie get_defined_constants(), um eine Liste aller definierten Konstanten zu erhalten.

Hinweis: Konstanten und (globale) Variablen befinden sich in unterschiedlichen Namensräumen. Das hat zum Beispiel zur Folge, dass TRUE und $TRUE etwas völlig Verschiedenes sind.

Falls Sie eine undefinierte Konstante verwenden, nimmt PHP an, dass Sie den Namen der Konstanten selbst meinen, so als ob Sie sie als einen string (CONSTANT vs "CONSTANT") aufgerufen hätten. Falls das passiert, wird Ihnen ein Fehler vom Typ E_NOTICE ausgegeben. Lesen Sie ebenfalls den entsprechenden Manualabschnitt, der erklärt, warum $foo[bar] falsch ist (zumindest solange Sie nicht zuvor bar mittels define() als Konstante definiert haben). Möchten Sie einfach nur nachprüfen, ob eine Konstante definiert ist, benutzen Sie die Funktion defined().

Das hier sind die Unterschiede zwischen Konstanten und Variablen:

  • Konstanten haben kein Dollarzeichen ($) vorangestellt;
  • Konstanten können nur über die Funktion define() definiert werden, nicht durch einfache Zuweisung;
  • Konstanten können überall definiert werden, und auf Ihren Wert können Sie ohne Rücksicht auf Namensraumregeln von Variablen zugreifen;
  • Sobald Konstanten definiert sind, können sie nicht neu definiert oder gelöscht werden; und
  • Konstanten können nur skalare Werte haben.

Beispiel #1 Definiton von Konstanten

<?php
define
("KONSTANTE""Hallo Welt.");
echo 
KONSTANTE;     // Ausgabe: "Hallo Welt."
echo Konstante;     // Ausgabe: "Konstante" und eine Notice.
?>

Beispiel #2 Definition von Konstanten unter Verwendung des const-Keywords

<?php
// Funktioniert seit PHP 5.3.0
const CONSTANT 'Hallo Welt';

echo 
CONSTANT;
?>

Lesen Sie ebenfalls den Abschnitt über Klassenkonstanten.



Magische Konstanten

PHP stellt jedem Skript zur Laufzeit eine Vielzahl von vordefinierten Konstanten zur Verfügung. Viele dieser Konstanten werden jedoch von verschiedenen Erweiterungen definiert, die nur zur Verfügung stehen, wenn diese Erweiterungen selbst zur Verfügung stehen, d.h. entweder über dynamisches Laden zur Laufzeit oder Einkompilieren.

Es gibt sieben magische Konstanten, die, abhängig davon, wo sie eingesetzt werden, einen unterschiedlichen Wert haben. Zum Beispiel hängt der Wert der Konstanten __LINE__ davon ab, in welcher Zeile ihres Skripts Sie diese Konstante verwenden. Diese besonderen Konstanten sind unabhängig von Groß-/Kleinschreibung und sind folgende:

Einige "magische" PHP-Konstanten
Name Beschreibung
__LINE__ Die aktuelle Zeilennummer einer Datei.
__FILE__ Der vollständige Pfad- und Dateiname einer Datei. Wird diese Konstante innerhalb einer nachgeladenen Datei verwendet, wird der Name dieser eingebundenen Datei zurückgegeben. Seit PHP 4.0.2 enthält __FILE__ immer einen absoluten Pfad mit aufgelösten Symlinks, während in älteren Versionen unter Umständen ein relativer Pfad enthalten sein kann.
__DIR__ Der Name des Verzeichnisses, in dem sich die Datei befindet. Wird die Konstante innerhalb eines Includes verwendet, wird das Verzeichnis der eingebundenen Datei zurückgegeben. Dies entspricht dem Verhalten von dirname(__FILE__). Der Verzeichnisname hat keinen beendenden Schrägstrich, sofern es sich nicht um das Rootverzeichnis handelt. (Hinzugefügt in PHP 5.3.0)
__FUNCTION__ Der Name der Funktion. (Hinzugefügt in PHP 4.3.0.) Mit PHP 5 enthält diese Konstante den Namen der Funktion, wie dieser deklariert wurde (Beachtung der Groß- und Kleinschreibung). In PHP 4 wird der Wert immer in Kleinschrift ausgegeben.
__CLASS__ Der Name einer Klasse. (Hinzugefügt in PHP 4.3.0.) Mit PHP 5 enthält diese Konstante den Namen der Klasse, wie dieser deklariert wurde (Beachtung der Groß- und Kleinschreibung). In PHP 4 wird der Wert immer in Kleinschrift ausgegeben.
__METHOD__ Der Name einer Klassenmethode. (Hinzugefügt in PHP 5.0.0.) Der Methodenname wird genauso zurückgegeben, wie er deklariert wurde (Beachtung der Groß- und Kleinschreibung).
__NAMESPACE__ Der Name des aktuellen Namespace (Beachtung der Groß- und Kleinschreibung). Diese Konstante wird zum Kompilierungszeitpunkt definiert. (Hinzugefügt in PHP 5.3.0)

Siehe auch get_class(), get_object_vars(), file_exists() und function_exists().




Ausdrücke

Ausdrücke (Expressions) sind die wichtigsten Bausteine von PHP. In PHP ist fast alles, was geschrieben wird, ein Ausdruck. Die einfachste, aber auch zutreffendste Definition für einen Ausdruck ist "alles, was einen Wert hat".

Die grundlegendsten Formen von Ausdrücken sind Konstanten und Variablen. Wenn man "$a = 5" schreibt, weist man $a den Ausdruck '5' zu. '5' hat offensichtlich den Wert 5. Anders ausgedrückt: '5' ist ein Ausdruck mit dem Wert 5 (in diesem Fall ist '5' eine Integer-Konstante).

Nach dieser Zuweisung würde man erwarten, dass der Wert von $a nun ebenfalls 5 ist; wenn man also $b = $a schreibt, sollte dasselbe dabei herauskommen, als hätte man $b = 5 geschrieben. Anders ausgedrückt: $a ist ebenfalls ein Ausdruck mit dem Wert 5. Wenn alles richtig funktioniert, wird genau das passieren.

Etwas kompliziertere Beispiele für Ausdrücke sind Funktionen. Betrachten wi zum Beispiel die folgende Funktion:

<?php
function foo ()
{
    return 
5;
}
?>

Angenommen, Sie sind mit dem Konzept von Funktionen vertraut (wenn Sie es nicht sind, lesen Sie das Kapitel über Funktionen), dann würden Sie davon ausgehen, dass die Eingabe von $c = foo() grundsätzlich dasselbe bedeutet, als würde man $c = 5 schreiben, und genau das trifft zu. Funktionen sind Ausdrücke mit dem Wert ihres Rückgabewertes. Da foo() den Wert 5 zurückgibt, ist der Wert des Ausdruckes 'foo()' 5. Normalerweise geben Funktionen nicht einfach einen statischen Wert zurück, sondern berechnen etwas.

Natürlich müssen Werte in PHP keine Integer-Zahlen sein, und oft sind sie es auch nicht. PHP unterstützt vier skalare Datentypen: integer (Ganzzahlen), float (Fließkommazahlen), string (Zeichenketten) und boolean (Wahrheitswerte). (Skalare sind Datentypen, die man, im Gegensatz zu zum Beispiel Arrays, nicht in kleinere Stücke 'brechen' kann.) PHP unsterstützt auch zwei zusammengesetzte (nicht-skalare) Datentypen: Arrays und Objekte. Jeder dieser Datentypen kann Variablen zugewiesen und von Funktionen zurückgegeben werden.

PHP fasst den Begriff Ausdruck aber noch viel weiter, wie es auch andere Programmiersprachen tun. PHP ist eine ausdrucksorientierte Sprache, in dem Sinne, dass fast alles einen Ausdruck darstellt. Zurück zu dem Beispiel, mit dem wir uns bereits beschäftigt haben: '$a = 5'. Es ist einfach zu erkennen, dass hier zwei Werte enthalten sind: Der Wert der Integer-Konstanten '5' und der Wert von $a, der auf 5 geändert wird. In Wirklichkeit ist aber noch ein weiterer Wert enthalten, nämlich der Wert der Zuweisung selbst. Die Zuweisung selbst enthält den zugewiesenen Wert, in diesem Fall 5. In der Praxis bedeutet dies, dass '$a = 5', egal was es tut, immer einen Ausdruck mit dem Wert 5 darstellt. Folglich ist '$b = ($a = 5)' gleichbedeutend mit '$a = 5; $b = 5;' (ein Semikolon markiert das Ende einer Anweisung). Da Wertzuweisungen von rechts nach links geparst werden, kann man auch '$b = $a = 5' schreiben.

Ein anderes gutes Beispiel für die Ausdrucksorientierung von PHP sind Prä- und Post-Inkrement sowie die entsprechenden Dekremente. Benutzer von PHP und vielen anderen Sprachen sind vermutlich mit den Notationen 'variable++' und 'variable--' vertraut. Dies sind Inkrement- und Dekrement-Operatoren. IN PHP/FI 2 hat das Statement '$a++' keinen Wert (es ist kein Ausdruck) und daher kann man es nicht als Wert zuweisen oder in irgendeiner Weise benutzen. PHP erweitert die Eigenschaften von Dekrement und Inkrement, indem es die beiden ebenfalls wie in C zu Ausdrücken macht. In PHP gibt es, wie in C, zwei Arten von Inkrementen - Prä-Inkrement und Post-Inkrement. Grundsätzlich erhöhen sowohl Prä- als auch Post-Inkrement den Wert der Variable, und der Effekt auf die Variable ist derselbe. Der Unterschied liegt im Wert des Inkrement-Ausdruckes. Das Prä-Inkrement, das '++$variable' geschrieben wird, enthält als Wert den Wert der erhöhten Variabe (PHP erhöht den Wert der Variablen, bevor es ihren Wert ausliest, daher der Name 'PRÄ-Inkrement'). Das Post-Inkrement, das '$variable++' geschrieben wird, enthält dagegen den ursprünglichen Wert der Variablen vor der Erhöhung (PHP erhöht den Wert der Variablen, nachdem es ihren Wert ausgelesen hat, daher der Name 'POST-Inkrement').

Ein sehr gebräuchlicher Typ von Ausdrücken sind Vergleichsausdrücke. Diese Ausdrücke geben entweder FALSE oder TRUE zurück. PHP unterstützt > (größer), >= (größer oder gleich), == (gleich), != (ungleich), < (kleiner), und <= (kleiner oder gleich). Die Sprache unterstützt weiterhin ein Set von absoluten Vergleichsoperatoren: === (inhalts- und typgleich) und !== (nicht inhalts- oder typgleich). Diese Ausdrücke werden meist in bedingten Anweisungen, wie z. B. in if-Anweisungen, verwendet.

Im letzten Beispiel für Ausdrücke befassen wir uns mit kombinierten Zuweisungs- und Operator-Ausdrücken. Wir wissen bereits, dass, wenn wir $a um 1 erhöhen wollen, wir einfach '$a++' oder '++$a' schreiben können. Aber was tut man, wenn man den Wert um mehr als eins erhöhen will, z. B. um 3? Man könnte mehrer Male '$a++' schreiben, aber das ist offensichtlich weder ein effizienter noch komfortabler Weg. Viel üblicher ist es, einfach '$a = $a + 3' zu schreiben. '$a + 3' gibt den Wert von $a plus 3 zurück, dieser wird wieder $a zugewiesen, was dazu führt, dass $a nun um 3 erhöht wurde. In PHP - wie in einigen anderen Programmiersprachen, z. B. in C - kann man dies aber noch kürzer schreiben, was mit der Zeit klarer wird und auch einfacher zu verstehen ist. Um 3 zu dem aktuellen Wert von $a hinzuzufügen, schreibt man '$a += 3'. Das bedeutet exakt: "Nimm den Wert von $a, addiere 3 hinzu und weise $a den entstandenen Wert zu". Zusätzlich dazu, dass diese Schreibweise kürzer und klarer ist, wird sie auch schneller ausgeführt. Der Wert von '$a += 3' ist, wie der Wert einer regulären Zuweisung, der zugewiesene Wert. Beachten Sie, dass dieser Wert NICHT 3, sondern dem kombinierten Wert von $a plus 3 entspricht (das ist der Wert, der $a zugewiesen wird). Jeder Operator, der zwei Elemente verbindet, kann in dieser Schreibweise verwendet werden, z. B. '$a -= 5' (vermindert den Wert von $a um 5) oder '$a *= 7' (multipliziert den Wert von $a mit 7 und weist das Ergebnis $a zu), usw.

Es gibt einen weiteren Ausdruck, der Ihnen vielleicht seltsam vorkommt, wenn Sie ihn bisher noch in keiner Programmiersprache kennengelernt haben, den dreifach konditionalen Operator:

<?php
$eins 
$zwei $drei
?>

Wenn der Wert des ersten Sub-Ausdruckes (hier: $eins) TRUE ist (d. h. nicht 0), dann wird der Wert des zweiten Subausdrucks (hier: $zwei) ausgewertet und ist das Ergebnis des konditionalen Ausdrucks. Andernfalls wird der dritte Subausdruck ausgewertet und dessen Wert zurückgegeben.

Das folgende Beispiel sollte das Verständnis von Prä- und Post-Inkrement und von Ausdrücken im Allgemeinen erleichtern:

<?php
function verdoppeln($i)
{
    return 
$i*2;
}
$b $a 5;        /* Weise den Variablen $a und $b den Wert 5 zu */
$c $a++;          /* Post-Inkrement, der urspruengliche Wert von $a (5)
                       wird $c zugewiesen. */
$e $d = ++$b;     /* Prae-Inkrement, der erhöhte Wert von $b (6) wird $d und
                       $e zugewiesen. */

/* An diesem Punkt sind $d und $e beide gleich 6 */

$f verdoppeln($d++);  /* Weise $f den doppelten Wert von $d vor
                           der Erhöhung um eins zu, 2*6 = 12 */
$g verdoppeln(++$e);  /* Weise $g den doppelten Wert von $e nach
                           der Erhoehung um eins zu, 2*7 = 14 to $g */
$h $g += 10;      /* Zuerst wird $g um 10 erhöht und hat damit den Wert
                       24. Der Wert dieser Zuweisung (24) wird dann $h
                       zugewiesen, womit $h ebenfalls den Wert von 24 hat. */
?>

Einige Ausdrücke können wie Anweisungen verwendet werden. In diesem Falle hat eine Anweisung die Form 'expr ;', dies meint einen Ausdruck gefolgt von einem Semikolon. In '$b = $a = 5;' ist '$a = 5' ein gültiger Ausdruck, aber für sich allein keine Anweisung. '$b = $a = 5;' ist jedoch eine gültige Anweisung.

Ein letzter Punkt, der noch zu erwähnen ist, ist der Wahrheitswert von Ausdrücken. In vielen Fällen, hauptsächlich in bedingten Anweisungen und Schleifen, ist man nicht am spezifischen Wert eines Ausdrucks interessiert, sondern kümmert sich nur darum, ob er TRUE oder FALSE bedeutet. Die Konstanten TRUE und FALSE (case-insensitiv) sind die beiden möglichen Wahrheitswerte. Wenn nötig wird ein Ausdruck automatisch in einen Boolschen Wert konvertiert. Wenn Sie mehr darüber erfahren wollen, lesen Sie den Abschnitt über Typecasting.

PHP stellt eine vollständige und mächtige Implementat von Ausdrücken bereit, deren vollständige Dokumentation den Rahmen dieses Manuals sprengen würde. Die obigen Beispiele sollten Ihnen einen guten Eindruck davon verschaffen, was Ausdrücke sind und wie man nützliche Ausdrücke konstruieren kann. Im Rest dieses Manuals werden wir expr schreiben, um ausdrücken, dass an dieser Stelle jeder gültige PHP-Ausdruck stehen kann.



Operatoren

Inhaltsverzeichnis

Ein Operator ist etwas das Sie mit einem oder mehreren Werten füttern (oder Ausdrücken, um im Programmierjargon zu sprechen) und Sie erhalten als Ergebnis einen anderen Wert (damit wird diese Konstruktion selbst zu einem Ausdruck). Als Eselsbrücke können Sie sich Operatoren als Funktionen oder Konstrukte vorstellen, die Ihnen einen Wert zurück liefern (ähnlich print) und alles, was Ihnen keinen Wert zurück liefert (ähnlich echo) als irgend etwas Anderes.

Es gibt drei Arten von Opratoren. Als erstes gibt es den unären Operator, der nur mit einem Wert umgehen kann, zum Beispiel ! (der Verneinungsoperator) oder ++ (der Inkrementoperator). Die zweite Gruppe sind die sogenannten binären Operatoren; diese Gruppe enthält die meisten Operatoren, die PHP unterstützt. Eine Liste dieser Operatoren finden Sie weiter unten im Abschnitt Operator-Rangfolge .

Die dritte Gruppe bildet der ternäre Operator : ?:. Dieser sollte eher benutzt werden um abhängig von einem dritten Ausdruck eine Auswahl zwischen zwei Ausdrücken zu treffen, als zwischen zwei Sätzen oder Pfaden der Programmausführung zu wählen. Übrigens ist es eine sehr gute Idee ternäre Ausdrücke in Klammern zu setzen.


Operator-Rangfolge

Die Operator-Rangfolge legt fest, wie "eng" ein Operator zwei Ausdrücke miteinander verbindet. Zum Beispiel ist das Ergebnis des Ausdruckes 1 + 5 * 3 16 und nicht 18, da der Multiplikations-Operator ("*") in der Rangfolge höher steht als der Additions-Operator ("+"). Wenn nötig, können Sie Klammern setzen, um die Rangfolge der Operatoren zu beeinflussen. Zum Beispiel ergibt: (1 + 5) * 3 18. Ist die Rangfolge der Operatoren gleich, wird links nach rechts Assoziativität benutzt.

Die folgende Tabelle zeigt die Rangfolge der Operatoren, oben steht der Operator mit dem höchsten Rang.

Operator-Rangfolge
Assoziativität Operator
keine Richtung new
rechts [
rechts ! ~ ++ -- (int) (float) (string) (array) (object) @
links * / %
links + - .
links << >>
keine Richtung < <= > >=
keine Richtung == != === !==
links &
links ^
links |
links &&
links ||
links ? :
rechts = += -= *= /= .= %= &= |= ^= <<= >>=
rechts print
links and
links xor
links or
links ,

Hinweis: Obwohl ! einen höheren Rang gegenüber = hat, erlaubt es Ihnen PHP immer noch ähnliche Ausdrücke wie den folgenden zu schreiben: if (!$a =foo()).In diesem Ausdruck wird die Ausgabe von foo() der Variablen $a zugewiesen.



Arithmetische Operatoren

Erinnern Sie sich noch an die Grundrechenarten aus der Schule? Die arithmetischen Operatoren funktionieren genauso:

Arithmetische Operatoren
Beispiel Name Ergebnis
$a + $b Addition Summe von $a und $b.
$a - $b Subtraktion Differenz von $a und $b.
$a * $b Multiplikation Produkt von $a und $b.
$a / $b Division Quotient von $a und $b.
$a % $b Modulus Rest von $a geteilt durch $b.

Der Divisions-Operator ("/") gibt immer eine Fließkommazahl zurück, sogar wenn die zwei Operanden Ganzzahlen sind (oder Zeichenketten, die nach Ganzzahlen umgewandelt wurden).

Siehe auch im Handbuch das Kapitel über Mathematische Funktionen.



Zuweisungsoperatoren

Der einfachste Zuweisungsoperator ist "=". Wahrscheinlich kommt man als erstes auf die Idee, ihn mit "ist gleich" zu bezeichnen. Das ist falsch. In Wirklichkeit bedeutet er, dass dem linken Operanden der Wert des Ausdrucks auf der rechten Seite zugewiesen wird (man müsste ihn also mit "wird gesetzt auf den Wert von" übersetzen).

Der Wert eines Zuweisungs-Ausdruckes ist der zugewiesene Wert. D.h. der Wert des Ausdruckes "$a = 3" ist 3. Das erlaubt es, einige raffinierte Dinge anzustellen:

<?php

$a 
= ($b 4) + 5// $a ist nun gleich 9 und $b wurde auf den Wert 4 gesetzt.

?>

Zusätzlich zu dem oben vorgestellten Zuweisungsoperator "=" gibt es "kombinierte Operatoren" für alle binären, arithmetischen und String-Operatoren, die es erlauben, den Wert einer Variablen in einem Ausdruck zu benutzen, und dieser anschließend das Ergebnis des Ausdrucks als neuen Wert zuzuweisen. Zum Beispiel:

<?php

$a 
3;
$a += 5// setzt $a auf den Wert 8, als ob wir geschrieben haetten: $a = $a + 5;
$b "Hallo ";
$b .= "Du!"// setzt $b auf den Wert "Hallo Du!", aequivalent zu 
             // $b = $b . "Du!";
?>

Man beachte, dass die Zuweisung nur den Wert der Ursprungsvarialbe der neuen Variable zuweist (Zuweisung als Wert, sie "kopiert"), weshalb sich Änderungen an der einen Variablen nicht auf die andere auswirken werden. Das kann wichtig sein, wenn man ein großes Array o. ä. in einer Schleife kopieren muss. Beginnend mit PHP 4 wird 'assignement by reference' (Zuweisung als Verweis), mit Hilfe der Schreibweise $var =&$othervar; unterstützt , das funktioniert jedoch nicht in PHP 3. 'Assignement by reference' bedeutet, dass beide Variablen nach der Zuweisung die selben Daten repräsentieren und nichts kopiert wird. Um mehr über Referenzen zu lernen, lesen Sie bitte den Abschnitt Referenzen erklärt.



Bit-Operatoren

Bit-Operatoren erlauben es, in einem Integer bestimmte Bits "ein- oder auszuschalten" (auf 0 oder 1 zu setzen). Wenn beide, der links- und rechtsseitige Parameter, Zeichenketten sind, arbeiten die Bit-Operatoren mit ASCII-Werten der einzelnen Zeichen.

<?php
echo 12 9// Ausgabe '5'

echo "12" "9"// Ausgabe: das Backspace-Zeichen (ascii 8)
                 // ('1' (ascii 49)) ^ ('9' (ascii 57)) = #8

echo "hallo" "hello"// Gibt die ASCII-Werte #0 #4 #0 #0 #0
                        // 'a' ^ 'e' = #4 aus
?>

Bit-Operatoren
Beispiel Name Ergebnis
$a & $b Und Bits, die in $a und $b gesetzt sind werden gesetzt.
$a | $b Oder Bits, die in $a oder $b gesetzt sind werden gesetzt.
$a ^ $b Entweder oder (Xor) Bits, die entweder in $a oder $b gesetzt sind, werden gesetzt aber nicht in beiden.
~ $a Nicht Die Bits, die in $a nicht gesetzt sind, werden gesetzt und umgekehrt.
$a << $b Nach links verschieben Verschiebung der Bits von $a um $b Stellen nach links (jede Stelle entspricht einer Mulitplikation mit zwei).
$a >> $b Nach rechts verschieben Verschiebt die Bits von $a um $b Stellen nach rechts (jede Stelle entspricht einer Division durch zwei).


Vergleichs-Operatoren

Vergleichs-Operatoren erlauben es - wie der Name schon sagt - zwei Werte zu vergleichen. Wenn Sie an Beispielen verschiedener auf Typen bezogener Vergleiche interessiert sind, können Sie sich PHP type comparison tables anschauen.

Vergleichsoperatoren
Beispiel Name Ergebnis
$a == $b Gleich Gibt TRUE zurück, wenn $a gleich $b ist.
$a === $b Identisch Gibt TRUE zurück wenn $a gleich $b ist und beide vom gleichen Typ sind (eingeführt in PHP 4).
$a != $b Ungleich Gibt TRUE zurück, wenn $a nicht gleich $b ist.
$a <> $b Ungleich Gibt TRUE zurück, wenn $a nicht gleich $b ist.
$a !== $b Nicht identisch Gibt TRUE zurück, wenn $a nicht gleich $b ist, oder wenn beide nicht vom gleichen Typ sind (eingeführt in PHP 4).
$a < $b Kleiner Als Gibt TRUE zurück, wenn $a kleiner als $b ist.
$a > $b Größer Als Gibt TRUE zurück, wenn $a größer als $b ist.
$a <= $b Kleiner Gleich Gibt TRUE zurück, wenn $a kleiner oder gleich $b ist.
$a >= $b Größer Gleich Gibt TRUE zurück, wenn $a größer oder gleich $b ist.

Ein weiter Vergleichs-Operator ist der "?:"- oder Trinitäts-Operator.

<?php
// Beispielanwendung für den Trinitäts-Operator
$action = (empty($_POST['action'])) ? 'standard' $_POST['action'];

// Obiges ist mit dieser if/else-Anweisung identisch
if (empty($_POST['action'])) {
    
$action 'standard';
} else {
    
$action $_POST['action'];
}
?>

Der Ausdruck (ausdr1) ? (ausdr2) : (ausdr3) gibt ausdr2 zurück, wenn ausdr1 TRUE zurückgibt und ausdr3, wenn ausdr1 FALSE zurückgibt.

Siehe auch strcasecmp(), strcmp(), Array-Operatoren und den Abschnitt über Typen.

Ternary Operator

Another conditional operator is the "?:" (or ternary) operator.

Beispiel #1 Assigning a default value

<?php
// Example usage for: Ternary Operator
$action = (empty($_POST['action'])) ? 'default' $_POST['action'];

// The above is identical to this if/else statement
if (empty($_POST['action'])) {
    
$action 'default';
} else {
    
$action $_POST['action'];
}

?>

The expression (expr1) ? (expr2) : (expr3) evaluates to expr2 if expr1 evaluates to TRUE, and expr3 if expr1 evaluates to FALSE.

Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.

Hinweis: Please note that the ternary operator is a statement, and that it doesn't evaluate to a variable, but to the result of a statement. This is important to know if you want to return a variable by reference. The statement return $var == 42 ? $a : $b; in a return-by-reference function will therefore not work and a warning is issued in later PHP versions.

Hinweis: It is recommended that you avoid "stacking" ternary expressions. PHP's behaviour when using more than one ternary operator within a single statement is non-obvious:

Beispiel #2 Non-obvious Ternary Behaviour

<?php
// on first glance, the following appears to output 'true'
echo (true?'true':false?'t':'f');

// however, the actual output of the above is 't'
// this is because ternary expressions are evaluated from left to right

// the following is a more obvious version of the same code as above
echo ((true 'true' 'false') ? 't' 'f');

// here, you can see that the first expression is evaluated to 'true', which
// in turn evaluates to (bool)true, thus returning the true branch of the
// second ternary expression.
?>




Fehler-Kontroll-Operatoren

PHP unterstützt einen Operator zur Fehlerkontrolle: Das @-Symbol. Stellt man das @ in PHP vor einen Ausdruck werden alle Fehlermeldungen, die von diesem Ausdruck erzeugt werden könnten, ignoriert.

Ist das track_errors-Feature aktiviert, werden alle Fehlermeldungen, die von diesem Ausdruck erzeugt werden, in der Variablen $php_errormsg gespeichert. Da diese Variable mit jedem neuen Auftreten eines Fehlers überschrieben wird, sollte man sie möglichst bald nach Verwendung des Ausdrucks überprüfen, wenn man mit ihr arbeiten will.

<?php
/* Beabsichtigter Dateifehler */
$my_file = @file ('nicht_vorhandene_Datei') or
    die (
"Datei konnte nicht geöffnetwerden: Fehler war:'$php_errormsg'");

// Das funktioniert bei jedem Ausdruck, nicht nur bei Funktionen:
$value = @$cache[$key]; 
// erzeugt keine Notice, falls der Index $key nicht vorhanden ist.

?>

Hinweis: Der @-Operator funktioniert nur bei Ausdrücken. Eine einfache Daumenregel: wenn Sie den Wert von etwas bestimmen können, dann können Sie den @-Operator davor schreiben. Zum Beispiel können Sie ihn vor Variablen, Funktionsaufrufe und vor include() setzen, vor Konstanten und so weiter. Nicht verwenden können Sie diesen Operator vor Funktions- oder Klassendefinitionen oder vor Kontrollstrukturen wie zum Beispiel if und foreach und so weiter.

Siehe auch error_reporting() und den Abschnitt über Error Handling and Logging Functions.

Hinweis: Der @ Fehler-Kontroll-Operator verhindert jedoch keine Meldungen, welche aus Fehlern beim Parsen resultieren.

Warnung

Zum gegenwärtigen Zeitpunkt deaktiviert der "@" Fehler-Kontrolloperator die Fehlermeldungen selbst bei kritischen Fehlern, die die Ausführung eines Skripts beenden. Unter anderem bedeutet das, wenn Sie "@" einer bestimmten Funktion voranstellen, diese aber nicht zur Verfügung steht oder falsch geschrieben wurde, Ihr PHP-Skript einfach beendet wird, ohne Hinweis auf die Ursache.



Operatoren zur Programmausführung

PHP unterstützt einen Operator zur Ausführung externer Programme: Die sog. Backticks (``). Achtung: Die Backticks sind keine einfachen Anführungszeichen! PHP versucht, den Text zwischen den Backticks als Kommandozeilen-Befehl auszuführen. Die Ausgabe des aufgerufenen Programms wird zurückgegeben (d.h. wird nicht einfach ausgegeben, sondern kann einer Variablen zugewiesen werden). Die Verwendung des Backtick-Operators ist mit shell_exec() identisch.

<?php
$output 
= `ls -al`;
echo 
"<pre>$output</pre>";
?>

Hinweis: Der Backtick-Operator steht nicht zur Verfügung, wenn Safe Mode aktiviert ist oder die Funktion shell_exec() deaktiviert wurde.

Siehe auch den Abschnitt über Funktionen zur Programmausführung, popen(), proc_open() und Using PHP from the commandline.



Inkrement- bzw. Dekrementoperatoren

PHP unterstützt Prä- und Post-Inkrement- und Dekrementoperatoren im Stil der Programmiersprache C.

Inkrement- und Dekrementoperatoren
Beispiel Name Auswirkung
++$a Prä-Inkrement Erhöht den Wert von $a um eins (inkrementiert $a) und gibt anschließend den neuen Wert von $a zurück.
$a++ Post-Inkrement Gibt zuerst den aktuellen Wert von $a zurück und erhöht dann den Wert von $a um eins.
--$a Prä-Dekrement Vermindert den Wert von $a um eins (dekrementiert $a) und gibt anschließend den neuen Wert von $a zurück.
$a-- Post-Dekrement Gibt zuerst den aktuellen Wert von $a zurück und erniedrigt dann den Wert von $a um eins.

Ein einfaches Beispiel-Skript:

<?php
echo "<h3>Post-Inkrement</h3>";
$a 5;
echo 
"Sollte 5 sein: " $a++ . "<br />\n";
echo 
"Sollte 6 sein: " $a "<br />\n";

echo 
"<h3>Pre-Inkrement</h3>";
$a 5;
echo 
"Sollte 6 sein: " . ++$a "<br />\n";
echo 
"Sollte 6 sein: " $a "<br />\n";

echo 
"<h3>Post-Dekrement</h3>";
$a 5;
echo 
"Sollte 5 sein: " $a-- . "<br />\n";
echo 
"Sollte 4 sein: " $a "<br />\n";

echo 
"<h3>Pre-Dekrement</h3>";
$a 5;
echo 
"Sollte 4 sein: " . --$a "<br />\n";
echo 
"Sollte 4 sein: " $a "<br />\n";
?>

PHP folgt bei der Behandlung arithmetischer Operationen an Zeichenvariablen der Perl-Konvention und nicht der von C. Zum Beispiel wird in Perl aus 'Z'+1 'AA', während aus 'Z'+1 in C '[' wird ( ord('Z') == 90, ord('[') == 91 ). Beachten Sie, dass Zeichenvariablen zwar inkrementiert aber nicht dekrementiert werden können.

Beispiel #1 Arithmetrische Operationen an Zeichenvariablen

<?php
$i 
'W';
for(
$n=0$n<6$n++)
  echo ++
$i "\n";

/*
  Erzeugt in etwa folgende Ausgabe:

X
Y
Z
AA
AB
AC

*/
?>



Logische Operatoren

Logische Operatoren
Beispiel Name Ergebnis
$a and $b Und TRUE wenn sowohl $a als auch $b TRUE ist.
$a or $b Oder TRUE wenn $a oder $b TRUE ist.
$a xor $b Entweder Oder TRUE wenn entweder $a oder $b TRUE ist, aber nicht beide.
! $a Nicht TRUE wenn $a nicht TRUE ist.
$a && $b Und TRUE wenn sowohl $a als auch $b TRUE ist.
$a || $b Oder TRUE wenn $a oder $b TRUE ist.

Der Grund dafür, dass es je zwei unterschiedliche Operatoren für die "Und"- und die "Oder"-Verknüpfung gibt ist der, dass die beiden Operatoren jeweils Rangfolgen haben. (siehe auch Operator-Rangfolge.)



Zeichenketten-Operatoren

Es gibt in PHP zwei Operatoren für string (Zeichenkette). Der erste ist der Vereinigungs-Operator ('.'), dessen Rückgabewert eine zusammengesetzte Zeichenkette aus dem rechten und dem linken Argument ist. Der zweite ist der Vereinigungs-Zuweisungsoperator ('.='), der das Argument auf der rechten Seite an das Argument der linken Seite anhängt. Siehe Zuweisungs-Operatoren für weitere Informationen.

<?php
$a 
"Hallo ";
$b $a "Welt!"// $b enthält jetzt den Text "Hallo Welt!"

$a "Hallo ";
$a .= "Welt!";    // $a enthält jetzt den Text "Hallo Welt!"
?>

Siehe auch die Abschnitte über Strings / Zeichenketten und String-Funktionen.



Array-Operatoren

Array-Operatoren
Beispiel Name Ergebnis
$a + $b Vereinigung Verinigung von $a und $b.
$a == $b Gleichwerigkeit TRUE wenn $a und $b die gleichen Schlüssel- und Wert-Paare enthalten.
$a === $b Identität TRUE wenn $a und $b die gleichen Schlüssel- und Wert-Paare in der gleichen Reihenfolge enthalten.
$a != $b Ungleichheit TRUE wenn $a nicht gleich $b ist.
$a <> $b Ungleichheit TRUE wenn $a nicht gleich $b ist.
$a !== $b nicht identisch TRUE wenn $a nicht identisch zu $b ist.

Der + Operator hängt das rechsstehende Array an das linksstehende Array an, wobei doppelte Schlüssel NICHT überschrieben werden.

<?php
$a 
= array("a" => "Apfel""b" => "Banane");
$b = array("a" =>"pear""b" => "Erdbeere""c" => "Kirsche");

$c $a $b// Verinigung von $a mit $b;
echo "Vereinigung von \$a mit \$b: \n";
var_dump($c);

$c $b $a// Vereinigung von $b mit $a;
echo "Vereinigung von \$b mit \$a: \n";
var_dump($c);
?>

Dieses Skript gibt folgendes aus:

Vereinigung von $a mit $b:
array(3) {
  ["a"]=>
  string(5) "Apfel"
  ["b"]=>
  string(6) "Banane"
  ["c"]=>
  string(7) "Kirsche"
}
Vereinigung von $b mit $a:
array(3) {
  ["a"]=>
  string(4) "pear"
  ["b"]=>
  string(8) "Erdbeere"
  ["c"]=>
  string(7) "Kirsche"
}

Beim Vergleich werden Arrayelemente als gleich angesehen, wenn diese dieselben Schlüssel und Werte beinhalten.

Beispiel #1 Array-Vergleiche

<?php
$a 
= array("Apfel""Banane");
$b = array(=> "Banane""0" => "Apfel");

var_dump($a == $b); // bool(true)
var_dump($a === $b); // bool(false)
?>

Siehe auch die Abschnitte über Arrays und Array-Funktionen.



Typ Operatoren

In PHP gibt es einen einzigen Typ Operator: instanceof. instanceof wird dazu verwendet um festzustellen, ob ein gegebenes Objekt ein Objekt ist, das zu einer bestimmten Klasse gehört.

instanceof wurde in PHP 5 eingeführt. Vorher wurde is_a() benutzt, aber is_a() ist veraltet und instanceof sollte stattdessen benutzt werden.

<?php
class A { }
class B { }

$ding = new A;

if ($ding instanceof A) {
    echo 'A';
}
if ($ding instanceof B) {
    echo 'B';
}
?>

Da $ding ein object vom Typ A und nicht von B ist, wird nur der Programmblock ausgeführt, der abhängig von Typ A ist:

A

See auch get_class() und is_a().




Kontrollstrukturen

Inhaltsverzeichnis


Einführung

Ein PHP-Skript besteht aus einer Abfolge von Anweisungen. Eine Anweisung kann eine Zuweisung, ein Funktionsaufruf oder ein bedingte Anweisung sein oder sogar eine Anweisung die nichts tut (eine leere Anweisung). Anweisungen enden in der Regel mit einem Semikolon. Anweisungen können des Weiteren in Anweisungsgruppen zusammengefasst werden indem sie in geschweifte Klammern eingeschlossen werden. Eine Anweisungsgruppe ist ebenfalls wieder eine Anweisung. Die verschiedenen Anweisungstypen werden in diesem Kapitel beschrieben.



if

Das if-Konstrukt ist eines der wichtigsten Features vieler Programmiersprachen, so auch in PHP, denn es ermöglicht die bedingte Ausführung von Kodefragmenten. PHP bietet eine if-Anweisung die der in C ähnelt:

if (expression)
  statement

expression wird wie im Abschnitt über Ausdrücke beschrieben zu einem boolschen Wahrheitswert ausgewertet. Evaluiert expression zu TRUE so wird statement von PHP ausgeführt, anderenfalls wird es ignoriert. Weitere Informationen dazu welche Werte als TRUE oder FALSE ausgewertet werden können Sie im Abschnitt 'Umwandlung zu boolean'.

Das folgende Beispiel würde a ist größer als b ausgeben wenn $a größer als $b ist:

<?php
if ($a $b)
  echo 
"a ist größer als b";
?>

Oft werden Sie mehr als eine Anweisung bedingt ausführen wollen. Dazu ist es natürlich nicht möglich jede Anweisung mit einer eigenen if-Anweisung zu versehen. Sie können statt dessen mehrere Anweisung zu einer Anweisungsgruppe zusammenfassen. So würde z.B. der folgende Programmcode a ist größer als b ausgeben und den Wert von $a an $b zuweisen:

<?php
if ($a $b) {
  echo 
"a ist größer als b";
  
$b $a;
}
?>

If-Anweisungen können beliebig oft ineinander verschachtelt werden und bieten Ihnen so vollständige Flexibilität für die bedingte Ausführung der verschiedenen Teile Ihres Programs.



else

Oft will man eine Anweisung ausführen wenn eine bestimmte Bedingung erfüllt ist und eine andere Anweisung wenn dies nicht der Fall ist. Dies ist der Einsatzzweck von else. else erweitert eine if-Anweisung um eine weitere Anweisung die dann ausgeführt werden soll wenn der Ausdruck in der if-Anweisung zu FALSE ausgewertet wird. Der folgende Programmkode würde z.B. a ist größer als b ausgeben wenn $a größer als b ist, ansonsten a ist NICHT größer als b

<?php
if ($a $b) {
  echo 
"a ist größer als b";
} else {
  echo 
"a ist NICHT größer als b";
}
?>

Die else Anweisung wird nur dann ausgeführt wenn der if Ausdruck und alle etwaigen elseif als FALSE ausgewertet wurden (siehe auch elseif).



elseif/else if

elseif, as its name suggests, is a combination of if and else. Like else, it extends an if statement to execute a different statement in case the original if expression evaluates to FALSE. However, unlike else, it will execute that alternative expression only if the elseif conditional expression evaluates to TRUE. For example, the following code would display a is bigger than b, a equal to b or a is smaller than b:

<?php
if ($a $b) {
    echo 
"a is bigger than b";
} elseif (
$a == $b) {
    echo 
"a is equal to b";
} else {
    echo 
"a is smaller than b";
}
?>

There may be several elseifs within the same if statement. The first elseif expression (if any) that evaluates to TRUE would be executed. In PHP, you can also write 'else if' (in two words) and the behavior would be identical to the one of 'elseif' (in a single word). The syntactic meaning is slightly different (if you're familiar with C, this is the same behavior) but the bottom line is that both would result in exactly the same behavior.

The elseif statement is only executed if the preceding if expression and any preceding elseif expressions evaluated to FALSE, and the current elseif expression evaluated to TRUE.

Hinweis: Note that elseif and else if will only be considered exactly the same when using curly brackets as in the above example. When using a colon to define your if/elseif conditions, you must not separate else if into two words, or PHP will fail with a parse error.

<?php

/* Incorrect Method: */
if($a $b):
    echo 
$a." is greater than ".$b;
else if(
$a == $b): // Will not compile.
    
echo "The above line causes a parse error.";
endif;


/* Correct Method: */
if($a $b):
    echo 
$a." is greater than ".$b;
elseif(
$a == $b): // Note the combination of the words.
    
echo $a." equals ".$b;
else:
    echo 
$a." is neither greater than or equal to ".$b;
endif;

?>



Alternative Syntax für Kontrollstrukturen

PHP bietet eine alternative Syntax für einige seiner Kontrollstrukturen an, namentlich für if, while, for, foreach und switch. In jedem Fall ist die Grundform der alternativen Syntax ein Wechsel der öffnenden Klammer gegen einen Doppelpunkt (:) und der schließenden Klammer in endif;, endwhile, endfor;, endforeach; respektive endswitch.

<?php if ($a == 5): ?>
A ist gleich 5
<?php endif; ?>

Im obigen Beispiel ist der HTML-Block "A ist gleich 5" in ein if-Statement verschachtelt, das in alternativer Syntax notiert ist. Der HTML-Block würde nur angezeigt werden, wenn $a gleich 5 ist.

Die alternative Syntax lässt sich ebenfalls auf else und elseif anwenden. Im Folgenden wird eine if-Struktur mit elseif- und else-Teilen im alternativen Format gezeigt:

<?php
if ($a == 5):
    echo 
"a gleich 5";
    echo 
"...";
elseif (
$a == 6):
    echo 
"a gleich 6";
    echo 
"!!!";
else:
    echo 
"a ist weder 5 noch 6";
endif;
?>

Siehe auch while, for und if für weitere Beispiele.



while

while loops are the simplest type of loop in PHP. They behave just like their C counterparts. The basic form of a while statement is:

while (expr)
    statement

The meaning of a while statement is simple. It tells PHP to execute the nested statement(s) repeatedly, as long as the while expression evaluates to TRUE. The value of the expression is checked each time at the beginning of the loop, so even if this value changes during the execution of the nested statement(s), execution will not stop until the end of the iteration (each time PHP runs the statements in the loop is one iteration). Sometimes, if the while expression evaluates to FALSE from the very beginning, the nested statement(s) won't even be run once.

Like with the if statement, you can group multiple statements within the same while loop by surrounding a group of statements with curly braces, or by using the alternate syntax:

while (expr):
    statement
    ...
endwhile;

The following examples are identical, and both print the numbers 1 through 10:

<?php
/* example 1 */

$i 1;
while (
$i <= 10) {
    echo 
$i++;  /* the printed value would be
                   $i before the increment
                   (post-increment) */
}

/* example 2 */

$i 1;
while (
$i <= 10):
    echo 
$i;
    
$i++;
endwhile;
?>



do-while

do-while-Schleifen sind sehr ähnlich zu while-Schleifen, außer dass der Wahrheitsausdruck erst am Ende eines jeden Durchlaufs statt zu dessen Beginn geprüft wird. Der Hauptunterschied zu einer normalen while-Schleife ist, dass die do-while-Schleife garantiert mindestens einmal durchlaufen wird (Der Wahrheitsausdruck wird ja nur am Ende jeden Durchlaufs geprüft), wohingegen es nicht zwingend ist, dass eine reguläre while-Schleife immer ausgeführt wird (hier wird der Wahrheitsausdruck bereits zu Beginn eines jeden Durchlaufs überprüft. Evaluiert er dabei zu FALSE, wird die Verarbeitung der Schleife sofort abgebrochen).

Es gibt nur eine Syntax für do-while-Schleifen:

<?php
$i 
0;
do {
    echo 
$i;
} while (
$i 0);
?>

Die obige Schleife wird exakt einmal durchlaufen, da nach dem ersten Durchlauf, wenn der Wahrheitsausdruck geprüft wird, dieser FALSE ergibt ($i ist nicht größer als 0), so dass die Schleifenausführung beendet wird.

Fortgeschrittenen C-Programmierern ist möglicherweise eine etwas andere Verwendung von do-while-Schleifen bekannt, die es erlaubt, die Ausführung in der Mitte des Codeblocks zu unterbrechen. Dies wird durch ein Kapseln in do-while(0) und die Verwendung des break-Statements erreicht. Das folgende Codefragment demonstriert dieses Verhalten:

<?php
do {
    if (
$i 5) {
        echo 
"i ist nicht groß genug";
        break;
    }
    
$i *= $factor;
    if (
$i $minimum_limit) {
        break;
    }
   echo 
"i ist ok";

    
/* i verarbeiten */

} while (0);
?>

Seien Sie nicht traurig, wenn Sie dies nicht oder nicht ganz verstehen. Sie können trotzdem Skripte - und wirklich leistungsfähige Skripte! - programmieren, ohne dieses "Feature" zu verwenden. Seit PHP 5.3.0 ist es möglich, statt dieses Hacks den goto-Operator zu verwenden.



for

for loops are the most complex loops in PHP. They behave like their C counterparts. The syntax of a for loop is:

for (expr1; expr2; expr3)
    statement

The first expression (expr1) is evaluated (executed) once unconditionally at the beginning of the loop.

In the beginning of each iteration, expr2 is evaluated. If it evaluates to TRUE, the loop continues and the nested statement(s) are executed. If it evaluates to FALSE, the execution of the loop ends.

At the end of each iteration, expr3 is evaluated (executed).

Each of the expressions can be empty or contain multiple expressions separated by commas. In expr2, all expressions separated by a comma are evaluated but the result is taken from the last part. expr2 being empty means the loop should be run indefinitely (PHP implicitly considers it as TRUE, like C). This may not be as useless as you might think, since often you'd want to end the loop using a conditional break statement instead of using the for truth expression.

Consider the following examples. All of them display the numbers 1 through 10:

<?php
/* example 1 */

for ($i 1$i <= 10$i++) {
    echo 
$i;
}

/* example 2 */

for ($i 1; ; $i++) {
    if (
$i 10) {
        break;
    }
    echo 
$i;
}

/* example 3 */

$i 1;
for (; ; ) {
    if (
$i 10) {
        break;
    }
    echo 
$i;
    
$i++;
}

/* example 4 */

for ($i 1$j 0$i <= 10$j += $i, print $i$i++);
?>

Of course, the first example appears to be the nicest one (or perhaps the fourth), but you may find that being able to use empty expressions in for loops comes in handy in many occasions.

PHP also supports the alternate "colon syntax" for for loops.

for (expr1; expr2; expr3):
    statement
    ...
endfor;

Its a common thing to many users to iterate though arrays like in the example below.

<?php
/*
* This is an array with some data we want to modify
* when running through the for loop.
*/
$people = Array(
        Array(
'name' => 'Kalle''salt' => 856412),
        Array(
'name' => 'Pierre''salt' => 215863)
        );

for(
$i 0$i sizeof($people); ++$i)
{
    
$people[$i]['salt'] = rand(000000999999);
}
?>

The problem lies in the second for expression. This code can be slow because it has to calculate the size of the array on each iteration. Since the size never change, it can be optimized easily using an intermediate variable to store the size and use in the loop instead of sizeof. The example below illustrates this:

<?php
$people 
= Array(
        Array(
'name' => 'Kalle''salt' => 856412),
        Array(
'name' => 'Pierre''salt' => 215863)
        );

for(
$i 0$size sizeof($people); $i $size; ++$i)
{
    
$people[$i]['salt'] = rand(000000999999);
}
?>



foreach

PHP 4 introduced a foreach construct, much like Perl and some other languages. This simply gives an easy way to iterate over arrays. foreach works only on arrays, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable. There are two syntaxes; the second is a minor but useful extension of the first:

foreach (array_expression as $value)
    statement
foreach (array_expression as $key => $value)
    statement

The first form loops over the array given by array_expression. On each loop, the value of the current element is assigned to $value and the internal array pointer is advanced by one (so on the next loop, you'll be looking at the next element).

The second form does the same thing, except that the current element's key will be assigned to the variable $key on each loop.

As of PHP 5, it is possible to iterate objects too.

Hinweis: When foreach first starts executing, the internal array pointer is automatically reset to the first element of the array. This means that you do not need to call reset() before a foreach loop.

Hinweis: Unless the array is referenced, foreach operates on a copy of the specified array and not the array itself. foreach has some side effects on the array pointer. Don't rely on the array pointer during or after the foreach without resetting it.

As of PHP 5, you can easily modify array's elements by preceding $value with &. This will assign reference instead of copying the value.

<?php
$arr 
= array(1234);
foreach (
$arr as &$value) {
    
$value $value 2;
}
// $arr is now array(2, 4, 6, 8)
unset($value); // break the reference with the last element
?>

This is possible only if iterated array can be referenced (i.e. is variable), that means the following code won't work:

<?php
foreach (array(1234) as &$value) {
    
$value $value 2;
}

?>

Warnung

Reference of a $value and the last array element remain even after the foreach loop. It is recommended to destroy it by unset().

Hinweis: foreach does not support the ability to suppress error messages using '@'.

You may have noticed that the following are functionally identical:

<?php
$arr 
= array("one""two""three");
reset($arr);
while (list(, 
$value) = each($arr)) {
    echo 
"Value: $value<br />\n";
}

foreach (
$arr as $value) {
    echo 
"Value: $value<br />\n";
}
?>

The following are also functionally identical:

<?php
$arr 
= array("one""two""three");
reset($arr);
while (list(
$key$value) = each($arr)) {
    echo 
"Key: $key; Value: $value<br />\n";
}

foreach (
$arr as $key => $value) {
    echo 
"Key: $key; Value: $value<br />\n";
}
?>

Some more examples to demonstrate usages:

<?php
/* foreach example 1: value only */

$a = array(12317);

foreach (
$a as $v) {
    echo 
"Current value of \$a: $v.\n";
}

/* foreach example 2: value (with its manual access notation printed for illustration) */

$a = array(12317);

$i 0/* for illustrative purposes only */

foreach ($a as $v) {
    echo 
"\$a[$i] => $v.\n";
    
$i++;
}

/* foreach example 3: key and value */

$a = array(
    
"one" => 1,
    
"two" => 2,
    
"three" => 3,
    
"seventeen" => 17
);

foreach (
$a as $k => $v) {
    echo 
"\$a[$k] => $v.\n";
}

/* foreach example 4: multi-dimensional arrays */
$a = array();
$a[0][0] = "a";
$a[0][1] = "b";
$a[1][0] = "y";
$a[1][1] = "z";

foreach (
$a as $v1) {
    foreach (
$v1 as $v2) {
        echo 
"$v2\n";
    }
}

/* foreach example 5: dynamic arrays */

foreach (array(12345) as $v) {
    echo 
"$v\n";
}
?>



break

break beendet die Ausführung der aktuellen for-, foreach-, while-, do-while- oder switch-Struktur.

break akzeptiert ein optionales numerisches Argument, das angibt, aus wievielen der es umschließenden verschachtelten Strukturen ausgebrochen werden soll.

<?php
$arr 
= array('eins''zwei''drei''vier''stop''fünf');
while (list(, 
$val) = each($arr)) {
    if (
$val == 'stop') {
        break;    
/* Sie könnten hier auch 'break 1;' schreiben. */
    
}
    echo 
"$val<br />\n";
}

/* Nutzung des optionalen Arguments. */

$i 0;
while (++
$i) {
    switch (
$i) {
    case 
5:
        echo 
"Bei 5<br />\n";
        break 
1;  /* Verlässt nur das switch. */
    
case 10:
        echo 
"Bei 10; breche ab<br />\n";
        break 
2;  /* Verlässt das switch und das while. */
    
default:
        break;
    }
}
?>



continue

continue wird innerhalb von Schleifen verwendet, um den Rest des aktuellen Schleifendurchlaufs abzubrechen und mit der Auswertung der nächsten Bedingung fortzufahren, um dann den nächsten Durchlauf zu beginnen.

Hinweis: Beachten Sie, dass in PHP das switch-Statement im Sinne von continue als Schleifenstruktur betrachtet wird.

continue akzeptiert ein optionales numerisches Argument, das angibt, wie viele Ebenen umschließender Schleifen bis zu ihrem Ende übersprungen werden sollen.

<?php
while (list($key$value) = each($arr)) {
    if (!(
$key 2)) { // ignoriere ungerade Werte
        
continue;
    }
    
mach_etwas_ungerade($value);
}

$i 0;
while (
$i++ < 5) {
    echo 
"Äußere<br />\n";
    while (
1) {
        echo 
"&nbsp;&nbsp;Mittlere<br />\n";
        while (
1) {
            echo 
"&nbsp;&nbsp;Innere<br />\n";
            continue 
3;
        }
        echo 
"Das hier wird nie ausgegeben.<br />\n";
    }
    echo 
"Das hier ebenfalls nicht.<br />\n";
}
?>

Das Weglassen des Semikolons nach continue kann zu unerwarteten Ergebnissen führen. Hier ist ein Beispiel, das zeigt, was Sie nicht tun sollten.

<?php
for ($i 0$i 5; ++$i) {
    if (
$i == 2)
        continue
    print 
"$i\n";
}
?>

Man könnte meinen, die Ausgabe wäre:

0
1
3
4

aber das Skript gibt in Wirklichkeit ...

2

... aus, da der Rückgabewert des print()-Aufrufs int(1) ist und daher als das oben genannte optionale numerische Argument betrachtet wird.



switch

The switch statement is similar to a series of IF statements on the same expression. In many occasions, you may want to compare the same variable (or expression) with many different values, and execute a different piece of code depending on which value it equals to. This is exactly what the switch statement is for.

Hinweis: Note that unlike some other languages, the continue statement applies to switch and acts similar to break. If you have a switch inside a loop and wish to continue to the next iteration of the outer loop, use continue 2.

Hinweis: Note that switch/case does loose comparision.

The following two examples are two different ways to write the same thing, one using a series of if and elseif statements, and the other using the switch statement:

Beispiel #1 switch structure

<?php
if ($i == 0) {
    echo 
"i equals 0";
} elseif (
$i == 1) {
    echo 
"i equals 1";
} elseif (
$i == 2) {
    echo 
"i equals 2";
}

switch (
$i) {
    case 
0:
        echo 
"i equals 0";
        break;
    case 
1:
        echo 
"i equals 1";
        break;
    case 
2:
        echo 
"i equals 2";
        break;
}
?>

Beispiel #2 switch structure allows usage of strings

<?php
switch ($i) {
    case 
"apple":
        echo 
"i is apple";
        break;
    case 
"bar":
        echo 
"i is bar";
        break;
    case 
"cake":
        echo 
"i is cake";
        break;
}
?>

It is important to understand how the switch statement is executed in order to avoid mistakes. The switch statement executes line by line (actually, statement by statement). In the beginning, no code is executed. Only when a case statement is found with a value that matches the value of the switch expression does PHP begin to execute the statements. PHP continues to execute the statements until the end of the switch block, or the first time it sees a break statement. If you don't write a break statement at the end of a case's statement list, PHP will go on executing the statements of the following case. For example:

<?php
switch ($i) {
    case 
0:
        echo 
"i equals 0";
    case 
1:
        echo 
"i equals 1";
    case 
2:
        echo 
"i equals 2";
}
?>

Here, if $i is equal to 0, PHP would execute all of the echo statements! If $i is equal to 1, PHP would execute the last two echo statements. You would get the expected behavior ('i equals 2' would be displayed) only if $i is equal to 2. Thus, it is important not to forget break statements (even though you may want to avoid supplying them on purpose under certain circumstances).

In a switch statement, the condition is evaluated only once and the result is compared to each case statement. In an elseif statement, the condition is evaluated again. If your condition is more complicated than a simple compare and/or is in a tight loop, a switch may be faster.

The statement list for a case can also be empty, which simply passes control into the statement list for the next case.

<?php
switch ($i) {
case 
0:
case 
1:
case 
2:
    echo 
"i is less than 3 but not negative";
    break;
case 
3:
    echo 
"i is 3";
}
?>

A special case is the default case. This case matches anything that wasn't matched by the other cases. For example:

<?php
switch ($i) {
    case 
0:
        echo 
"i equals 0";
        break;
    case 
1:
        echo 
"i equals 1";
        break;
    case 
2:
        echo 
"i equals 2";
        break;
    default:
       echo 
"i is not equal to 0, 1 or 2";
}
?>

The case expression may be any expression that evaluates to a simple type, that is, integer or floating-point numbers and strings. Arrays or objects cannot be used here unless they are dereferenced to a simple type.

The alternative syntax for control structures is supported with switches. For more information, see Alternative syntax for control structures.

<?php
switch ($i):
    case 
0:
        echo 
"i equals 0";
        break;
    case 
1:
        echo 
"i equals 1";
        break;
    case 
2:
        echo 
"i equals 2";
        break;
    default:
        echo 
"i is not equal to 0, 1 or 2";
endswitch;
?>

Its possible to use a semicolon instead of a colon after a case like:

<?php
switch($beer)
{
    case 
'tuborg';
    case 
'carlsberg';
    case 
'heineken';
        echo 
'Good choice';
    break;
    default;
        echo 
'Please make a new selection...';
    break;
}
?>



declare

Das declare-Konstrukt wird verwendet, um Ausführungsdirektiven für einen Codeblock festzulegen. Die Syntax von declare ist ähnliche wie die Syntax anderer Ablauf-Kontrollstrukturen:

declare (directive)
    statement

Die directive-Sektion erlaubt es, das Verhalten des declare-Blocks anzugeben. Aktuell werden zwei Direktiven unterstützt: die ticks-Direktive (siehe unten für weitere Informationen über die ticks-Direktive) und die encoding-Direktive (siehe unten für weitere Informationen über die encoding-Direktive).

Hinweis: Die Encoding-Direktive wurde in PHP 5.3.0 hinzugefügt.

Der statement-Teil des declare-Blocks wird ausgeführt - wie genau die Ausführung aussieht und welche Seiteneffekte während der Ausführung auftreten können, ist abhängig von der im directive-Block gesetzten Direktive.

Das declare-Konstrukt kann außerdem im globalen Sichtbarkeitsbereich verwendet werden, es hat dann Auswirkungen auf den gesamten folgenden Code (wird die Datei mit der declare-Anweisung inkludiert, hat die Anweisung jedoch keine Auswirkung auf das einbindende File).

<?php
// dies sind gleichwertige Schreibweisen:

// Sie können diese Schreibweise verwenden:
declare(ticks=1) {
    
// hier das vollständige Skript einfügen
}

// oder diese:
declare(ticks=1);
// hier das vollständige Skript einfügen
?>

Ticks

Achtung

Mit PHP 5.3.0 gilt Ticks als veraltet und wird mit PHP 6.0.0 entfernt.

Ein Tick ist ein Event, das alle N Low-Level-Statements auftritt, die vom Parser innerhalb des declare-Blocks ausgeführt werden. Der Wert für N wird durch die Verwendung von ticks=N innerhalb der directive-Sektion des declare-Blocks angegeben.

Das/die bei jedem Tick auftretenden Event(s) werden durch die Verwendung der Funktion register_tick_function() angegeben. Betrachten Sie das folgende Beispiel für mehr Details. Beachten Sie, dass mehr als ein Event bei jedem Tick auftreten kann.

Beispiel #1 Eine PHP-Codesektion profilen

<?php
// Eine Funktion, die die Zeit aufzeichnet, zu der sie aufgerufen wurde
function profile($dump FALSE)
{
    static 
$profile;

    
// Gibt die im Profil gespeicherten Zeiten zurück und löscht sie danach
    
if ($dump) {
        
$temp $profile;
        unset(
$profile);
        return 
$temp;
    }

    
$profile[] = microtime();
}

// Einen Tick-Handler angeben
register_tick_function("profile");

// Die Funktion vor dem declare-Block initialisieren
profile();

// Einen Codeblock ausführen, bei jedem zweiten Statement einen Tick auslösen
declare(ticks=2) {
    for (
$x 1$x 50; ++$x) {
        echo 
similar_text(md5($x), md5($x*$x)), "<br />;";
    }
}

// Die im Profiler gespeicherten Daten anzeigen
print_r(profile(TRUE));
?>

Das Beispiel analysiert den PHP-Code im 'declare'-Block und erfasst die Zeiten, an denen jedes zweite Low-Level-Statement innerhalb des Blocks ausgeführt wurde. Diese Information kann danach verwendet werden, um die langsamen Bereiche eines bestimmten Codesegments ausfindig zu machen. Dieser Prozess kann auch mit anderen Methoden ausgeführt werden - die Verwendung von Ticks ist einfacher und leichter zu implementieren.

Ticks sind sehr geeignet für das Debugging, die Implementierung einfachen Multitaskings, I/O-Verarbeitung im Hintergrund und viele weitere Anwendungen.

Siehe auch register_tick_function() und unregister_tick_function().

Encoding

Das Encoding eines Skripts kann pro Skript mittels der Encoding-Direktive festgelegt werden.

Beispiel #2 Das Encoding eines Skripts deklarieren.

<?php
declare(encoding='ISO-8859-1');
// hier folgt der Code
?>

Achtung

Die einzig zulässige Syntax für ein declare, das mit Namespaces kombiniert wird, ist declare(encoding='...');, wobei ... der encodete Wert ist. declare(encoding='...') {} bewirkt einen Parse-Error, wenn es mit Namespaces kombiniert wird.

Der encodete declare-Wert wird in PHP 5.3 ignoriert, sofern PHP nicht mit --enable-zend-multibyte kompiliert wurde. In PHP 6.0.0 wird die encoding-Direktive verwendet, um den Scanner darüber zu informieren, mit welchem Encoding die Datei erstellt wurde. Zulässige Werte sind Encodingbezeichnungen wie UTF-8.



return

If called from within a function, the return() statement immediately ends execution of the current function, and returns its argument as the value of the function call. return() will also end the execution of an eval() statement or script file.

If called from the global scope, then execution of the current script file is ended. If the current script file was include()ed or require()ed, then control is passed back to the calling file. Furthermore, if the current script file was include()ed, then the value given to return() will be returned as the value of the include() call. If return() is called from within the main script file, then script execution ends. If the current script file was named by the auto_prepend_file or auto_append_file configuration options in php.ini, then that script file's execution is ended.

For more information, see Returning values.

Hinweis: Note that since return() is a language construct and not a function, the parentheses surrounding its arguments are not required. It is common to leave them out, and you actually should do so as PHP has less work to do in this case.

Hinweis: If no parameter is supplied, then the parentheses must be omitted and NULL will be returned. Calling return() with parentheses but with no arguments will result in a parse error.

Hinweis: You should never use parentheses around your return variable when returning by reference, as this will not work. You can only return variables by reference, not the result of a statement. If you use return ($a); then you're not returning a variable, but the result of the expression ($a) (which is, of course, the value of $a).



require()

require() entspricht im Wesentlichen include(), wirft aber im Fehlerfall einen E_ERROR Fehler. Es beendet also die Programmausführung während include() nur eine Warnung (E_WARNING) generiert und so die weitere Programmausführung gestattet.

Weitere Informationen hierzu finden Sie in der include()-Dokumentation.



include()

The include() statement includes and evaluates the specified file.

The documentation below also applies to require().

Files are included based on the file path given or, if none is given, the include_path specified. The include() construct will emit a warning if it cannot find a file; this is different behavior from require(), which will emit a fatal error.

If a path is defined (full or relative), the include_path will be ignored altogether. For example, if a filename begins with ../, the parser will look in the parent directory to find the requested file.

For more information on how PHP handles including files and the include path, see the documentation for include_path.

When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward. However, all functions and classes defined in the included file have the global scope.

Beispiel #1 Basic include() example

vars.php
<?php

$color 
'green';
$fruit 'apple';

?>

test.php
<?php

echo "A $color $fruit"// A

include 'vars.php';

echo 
"A $color $fruit"// A green apple

?>

If the include occurs inside a function within the calling file, then all of the code contained in the called file will behave as though it had been defined inside that function. So, it will follow the variable scope of that function. An exception to this rule are magic constants which are evaluated by the parser before the include occurs.

Beispiel #2 Including within functions

<?php

function foo()
{
    global 
$color;

    include 
'vars.php';

    echo 
"A $color $fruit";
}

/* vars.php is in the scope of foo() so     *
* $fruit is NOT available outside of this  *
* scope.  $color is because we declared it *
* as global.                               */

foo();                    // A green apple
echo "A $color $fruit";   // A green

?>

When a file is included, parsing drops out of PHP mode and into HTML mode at the beginning of the target file, and resumes again at the end. For this reason, any code inside the target file which should be executed as PHP code must be enclosed within valid PHP start and end tags.

If "URL fopen wrappers" are enabled in PHP (which they are in the default configuration), you can specify the file to be included using a URL (via HTTP or other supported wrapper - see List of Supported Protocols/Wrappers for a list of protocols) instead of a local pathname. If the target server interprets the target file as PHP code, variables may be passed to the included file using a URL request string as used with HTTP GET. This is not strictly speaking the same thing as including the file and having it inherit the parent file's variable scope; the script is actually being run on the remote server and the result is then being included into the local script.

Warnung

PHP-Versionen kleiner 4.3.0 für Windows, erlauben den Zugriff auf Remote-Dateien mit dieser Funktion nicht, selbst wenn allow_url_fopen aktiviert ist.

Beispiel #3 include() through HTTP

<?php

/* This example assumes that www.example.com is configured to parse .php
* files and not .txt files. Also, 'Works' here means that the variables
* $foo and $bar are available within the included file. */

// Won't work; file.txt wasn't handled by www.example.com as PHP
include 'http://www.example.com/file.txt?foo=1&bar=2';

// Won't work; looks for a file named 'file.php?foo=1&bar=2' on the
// local filesystem.
include 'file.php?foo=1&bar=2';

// Works.
include 'http://www.example.com/file.php?foo=1&bar=2';

$foo 1;
$bar 2;
include 
'file.txt';  // Works.
include 'file.php';  // Works.

?>

Warnung

Security warning

Remote file may be processed at the remote server (depending on the file extension and the fact if the remote server runs PHP or not) but it still has to produce a valid PHP script because it will be processed at the local server. If the file from the remote server should be processed there and outputted only, readfile() is much better function to use. Otherwise, special care should be taken to secure the remote script to produce a valid and desired code.

See also Remote files, fopen() and file() for related information.

Handling Returns: It is possible to execute a return() statement inside an included file in order to terminate processing in that file and return to the script which called it. Also, it's possible to return values from included files. You can take the value of the include call as you would a normal function. This is not, however, possible when including remote files unless the output of the remote file has valid PHP start and end tags (as with any local file). You can declare the needed variables within those tags and they will be introduced at whichever point the file was included.

Because include() is a special language construct, parentheses are not needed around its argument. Take care when comparing return value.

Beispiel #4 Comparing return value of include

<?php
// won't work, evaluated as include(('vars.php') == 'OK'), i.e. include('')
if (include('vars.php') == 'OK') {
    echo 
'OK';
}

// works
if ((include 'vars.php') == 'OK') {
    echo 
'OK';
}
?>

Beispiel #5 include() and the return() statement

return.php
<?php

$var 
'PHP';

return 
$var;

?>

noreturn.php
<?php

$var 
'PHP';

?>

testreturns.php
<?php

$foo 
= include 'return.php';

echo 
$foo// prints 'PHP'

$bar = include 'noreturn.php';

echo 
$bar// prints 1

?>

$bar is the value 1 because the include was successful. Notice the difference between the above examples. The first uses return() within the included file while the other does not. If the file can't be included, FALSE is returned and E_WARNING is issued.

If there are functions defined in the included file, they can be used in the main file independent if they are before return() or after. If the file is included twice, PHP 5 issues fatal error because functions were already declared, while PHP 4 doesn't complain about functions defined after return(). It is recommended to use include_once() instead of checking if the file was already included and conditionally return inside the included file.

Another way to "include" a PHP file into a variable is to capture the output by using the Output Control Functions with include(). For example:

Beispiel #6 Using output buffering to include a PHP file into a string

<?php
$string 
get_include_contents('somefile.php');

function 
get_include_contents($filename) {
    if (
is_file($filename)) {
        
ob_start();
        include 
$filename;
        
$contents ob_get_contents();
        
ob_end_clean();
        return 
$contents;
    }
    return 
false;
}

?>

In order to automatically include files within scripts, see also the auto_prepend_file and auto_append_file configuration options in php.ini.

Hinweis: Da dies ein Sprachkonstrukt und keine Funktion ist, können Sie dieses nicht mit Variablenfunktionen verwenden.

See also require(), require_once(), include_once(), get_included_files(), readfile(), virtual(), and include_path.



require_once()

Die require_once() entspricht im Wesentlichen der Funktion require(). PHP prüft hier allerdings ob die gewünschte Datei bereits eingebunden wurde und wird sie in diesem Fall nicht ein weiteres mal einbinden.

Nähere Informationen zum Verhalten von _once und wie es sich von seinem nicht-_once-Gegenstück unterscheidet finden Sie in der Dokumentation zu include_once().



include_once()

The include_once() statement includes and evaluates the specified file during the execution of the script. This is a behavior similar to the include() statement, with the only difference being that if the code from a file has already been included, it will not be included again. As the name suggests, it will be included just once.

include_once() may be used in cases where the same file might be included and evaluated more than once during a particular execution of a script, so in this case it may help avoid problems such as function redefinitions, variable value reassignments, etc.

See the include() documentation for information about how this function works.

Hinweis: With PHP 4, _once functionality differs with case-insensitive operating systems (like Windows) so for example:

Beispiel #1 include_once() with a case insensitive OS in PHP 4

<?php
include_once "a.php"// this will include a.php
include_once "A.php"// this will include a.php again! (PHP 4 only)
?>


This behaviour changed in PHP 5, so for example with Windows the path is normalized first so that C:\PROGRA~1\A.php is realized the same as C:\Program Files\a.php and the file is included just once.



goto

Der goto-Operator kann benutzt werden um innerhalb eines Programs zu einer anderen Anweisung zu springen. Die Zielanweisung wird durch einen Namen gefolgt von einem Doppelpunkt festgelegt und der goto-Anweisung wird der entsprechende Zielname angefügt.

Beispiel #1 goto-Beispiel

<?php
goto a;
echo 
'Foo';
 
a:
echo 
'Bar';
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

Bar

Hinweis: Der goto-Operator ist ab PHP 5.3 verfügbar.

Warnung

Es ist nicht gestattet in eine Schleife oder eine Switch-Anweisung hineinzuspringen, in so einem Fall wird ein fataler Fehler geworfen.




Funktionen

Inhaltsverzeichnis


Vom Nutzer definierte Funktionen

Eine Funktion kann wie folgt definiert werden:

Beispiel #1 Pseudocode zur Demonstration der Nutzung von Variablen

<?php
function foo ($arg_1$arg_2, ..., $arg_n)
{
    echo 
"Beispielfunktion.\n";
    return 
$retval;
}
?>

Jeder beliebige korrekte PHP-Code kann in einer Funktion vorkommen, sogar andere Funktionen und Klassen-Definitionen.

Für Funktionsnamen gelten in PHP die gleichen Regeln wie für andere Bezeichner. Ein gültiger Funktionsname beginnt mit einem Buchstaben oder Unterstrich gefolgt von einer beliebigen Anzahl von Buchstaben, Ziffern und Unterstrichen. Als regulärer Ausdruck wird dies so ausgedrückt: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*.

Tipp

Siehe auch Userland Naming Guide.

Es ist nicht erforderlich, dass Funktionen bereits definiert sein müssen, wenn auf sie verviesen wird, außer wenn eine Funktion nur bedingt definiert wird, wie in den beiden untenstehenden Beispielen gezeigt.

Wenn eine Funktion nur unter bestimmten Bedingungen definiert wird, muss die Definition dieser Funktion noch vor deren Aufruf abgearbeitet werden.

Beispiel #2 Bedingte Funktionen

<?php

$makefoo 
true;

/* Wir können foo() von hier aus nicht
   aufrufen, da sie noch nicht existiert,
   aber wir können bar() aufrufen */

bar();

if (
$makefoo) {
  function 
foo ()
  {
    echo 
"Ich existiere nicht, bis mich die Programmausführung erreicht hat.\n";
  }
}

/* Nun können wir foo() sicher aufrufen,
   da $makefoo als true ausgewertet wurde */

if ($makefoofoo();

function 
bar()
{
  echo 
"Ich existiere sofort nach Programmstart.\n";
}

?>

Beispiel #3 Funktionen innerhalb von Funktionen

<?php
function foo()
{
  function 
bar()
  {
    echo 
"Ich existiere nicht, bis foo() aufgerufen wurde.\n";
  }
}

/* Wir können bar() noch nicht
   aufrufen, da es nicht existiert */

foo();

/* Nun können wir auch bar() aufrufen,
   da sie durch die Abarbeitung von
   foo() verfügbar gemacht wurde */

bar();

?>

Alle Funktionen und Klassen in PHP existieren im globalen Namensraum - sie können außerhalb von Funktionen aufgerufen werden, selbst wenn sie innerhalb einer Funktion definiert wurden und umgekehrt.

PHP unterstützt weder das Überladen von Funktionen, noch ist es möglich, zuvor deklarierte Funktionen neu zu definieren oder die Definition zu löschen.

Hinweis: Groß- und Kleinschreibung spielt zwar bei Funktionsnamen keine Rolle, es empfiehlt sich aber trotzdem bei Funktionsaufrufen die gleiche Schreibweise wie in der Deklaration zu benutzen.

Sowohl eine variable Anzahl Parameter als auch Vorgabewerte für Parameter werden in Funktionen unterstützt. Siehe auch die Funktionsreferenzen für func_num_args(), func_get_arg() und func_get_args() für weitere Informationen.

Es ist in PHP möglich, Funktionen rekursiv aufzurufen. Sie sollten aber rekursive Aufrufe mit einer Rekursionstiefe von mehr als 100-200 vermeiden, da diese zu einem Stacküberlauf und damit zum Programmabbruch führen können.

Beispiel #4 Rekursive Funktionen

<?php
function recursion($a)
{
    if (
$a 20) {
        echo 
"$a\n";
        
recursion($a 1);
    }
}
?>



Funktionsparameter

Mit einer Parameterliste kann man Informationen an eine Funktion übergeben. Die Parameterliste ist eine durch Kommas getrennte Liste von Ausdrücken.

PHP unterstützt die Weitergabe von Parametern als Werte (das ist der Standard), als Verweise und als Vorgabewerte. Eine variable Anzahl von Parametern wird ebenfalls unterstützt, siehe auch die Funktionsreferenzen für func_num_args(), func_get_arg() und func_get_args() für weitere Informationen.

Beispiel #1 Arrays an Funktionen übergeben

<?php
function rechne_array($eingabe)
{
    echo 
"$eingabe[0] + $eingabe[1] = "$eingabe[0]+$eingabe[1];
}
?>

Verweise als Parameter übergeben

Normalerweise werden den Funktionen Werte als Parameter übermittelt. Wenn man den Wert dieses Parameters innerhalb der Funktion ändert, bleibt der Parameter außerhalb der Funktion unverändert. Wollen Sie aber erreichen, dass die Änderung auch außerhalb der Funktion sichtbar wird, müssen Sie die Parameter als Verweise (Referenzen) übergeben.

Wenn eine Funktion einen Parameter generell als Verweis behandeln soll, setzt man in der Funktionsdefinition ein kaufmännisches Und (&) vor den Parameternamen:

Beispiel #2 Übergeben von Funktionsparametern als Verweis

<?php
function fuege_etwas_anderes_an (&$string)
{
    
$string .= 'und nun zu etwas anderem.';
}
$str 'Dies ist ein String, ';
fuege_etwas_anderes_an ($str);
echo 
$str// Ausgabe: 'Dies ist ein String, und nun zu etwas anderem.'
?>

Vorgabewerte für Parameter

Eine Funktion kann C++-artige Vorgabewerte für skalare Parameter wie folgt definieren:

Beispiel #3 Einsatz von Vorgabeparametern

<?php
function machkaffee ($typ "Cappucino")
{
    return 
"Ich mache eine Tasse $typ.\n";
}
echo 
machkaffee ();
echo 
machkaffee (null);
echo 
machkaffee ("Espresso");
?>

Die Ausgabe von diesem kleinen Skript ist:


Ich mache eine Tasse Cappucino.
Ich mache eine Tasse.
Ich mache eine Tasse Espresso.

PHP gestattet es, Arrays und den speziellen Typ NULL als Vorgabewert zu nutzen, zum Beispiel:

Beispiel #4 Nichtskalare Typen als Vorgabewert

<?php
function makecoffee ($types = array("cappuccino"), $coffeeMaker NULL)
{
    
$device is_null($coffeeMaker) ? "hands" $coffeeMaker;
    return 
"Ich mache eine Tasse ".join(", "$types)." mit $device.\n";
}
echo 
makecoffee ();
echo 
makecoffee (array("cappuccino""lavazza"), "teapot");
?>

Der Vorgabewert muss ein konstanter Ausdruck sein, darf also zum Beispiel keine Variable, Eigenschaft einer Klasse oder ein Funktionsaufruf sein.

Bitte beachten Sie, dass alle Vorgabewerte rechts von den Nicht-Vorgabeparametern stehen sollten - sonst wird es nicht funktionieren. Betrachten Sie folgendes Beispiel:

Beispiel #5 Ungültige Anwendung von Vorgabewerten

<?php
function mach_joghurt ($typ "rechtsdrehendes"$geschmack)
{
    return 
"Mache einen Becher $typ $geschmack-joghurt.\n";
}

echo 
mach_joghurt ("Brombeer");   // arbeitet nicht wie erwartet
?>

Die Ausgabe dieses Beispiels ist:


Warning: Missing argument 2 in call to mach_joghurt() in
/usr/local/etc/httpd/htdocs/phptest/functest.html on line 41
Mache einen Becher Brombeer-joghurt.

Nun vergleichen Sie bitte oberes Beispiel mit folgendem:

Beispiel #6 Richtiger Einsatz von Vorgabewerten

<?php
function mach_joghurt ($geschmack$typ "rechtsdrehendes")
{
    return 
"Mache einen Becher $typ $geschmack-Joghurt.\n";
}

echo 
mach_joghurt ("Brombeer");   // arbeitet wie erwartet.
?>

... und jetzt ist die Ausgabe:


Mache einen Becher rechtsdrehendes Brombeer-Joghurt.

Hinweis: Das Setzen von Standardwerten für Argumente, die als Referenz übergeben werden ("passed by reference") wird seit PHP 5 unterstützt.

Variable Anzahl von Parametern

Beginnend mit PHP 4 wird eine variable Anzahl von Parametern in benutzerdefinierten Funktionen unterstützt. Das Handling dieser Parameter fällt mittels der Funktionen func_num_args(), func_get_arg() und func_get_args() sehr leicht.

Es ist keine spezielle Syntax erforderlich. Die Parameter können wie gehabt explizit in den Funktionsdeklarationen angegeben werden und werden sich wie gewohnt verhalten.



Rückgabewerte

Sie können Werte mit dem optionalen Befehl "return" zurückgeben. Es können Variablen jeden Typs zurückgegeben werden, auch Arrays oder Objekte. Dies beendet sofort die Funktion und die Kontrolle wird wieder an die aufrufende Zeile zurückgegeben. Weitere Informationen finden Sie unter return().

Beispiel #1 Einsatz von return()

<?php
function quadrat ($zahl)
{
    return 
$zahl $zahl;
}
echo 
quadrat (4);   // gibt '16' aus.

?>

Es ist nicht möglich, mehrere Werte von einer Funktion zurückzugeben. Ein ähnliches Resultat kann man aber durch die Rückgabe von Arrays erreichen.

Beispiel #2 Rückgabe mehrere Werte in Arrays

<?php
function kleine_zahlen()
{
   return array (
012);
}
list (
$null$eins$zwei) = kleine_zahlen();
?>

Um von einer Funktion eine Referenz zurückzugeben, müssen Sie den Referenz-Operator & sowohl in der Funktionsdeklaration, als auch bei der Zuweisung des zurückgegebenen Wertes verwenden:

Beispiel #3 Rückgabe von Referenzen

<?php
function &returniere_referenz()
{
    return 
$einereferenz;
}

$neuereferenz =& returniere_referenz();
?>

Weitere Informationen über Referenzen finden Sie im Kapitel Referenzen in PHP.



Variablenfunktionen

PHP unterstützt das Konzept der Variablenfunktionen. Wenn Sie an das Ende einer Variablen Klammern hängen, versucht PHP eine Funktion aufzurufen, deren Name der aktuelle Wert der Variablen ist. Dies kann unter anderem für Callbacks, Funktionstabellen, usw. genutzt werden.

Variablenfunktionen funktionieren nicht mit Sprachkonstrukten wie echo(), print(), unset(), isset(), empty(), include() und require(). Sie müssen Ihre eigenen Wrapperfunktionen verwenden, um diese Konstrukte als variable Funktionen benutzen zu können.

Beispiel #1 Beispiel für Variablenfunktionen

<?php
function foo()
{
    echo 
"In foo()<br />\n";
}

function 
bar($arg '')
{
    echo 
"In bar(); der Parameter ist '$arg'.<br />\n";
}

// Dies ist eine Wrapperfunkiton für echo
function echoit($string)
{
    echo 
$string;
}

$func 'foo';
$func();        // Dies ruft foo() auf

$func 'bar';
$func('test');  // Dies ruft bar() auf

$func 'echoit';
$func('test');  // Dies ruft echoit() auf
?>

Sie können auch die Methode eines Objektes mittels der variablen Funktionen aufrufen.

Beispiel #2 Variable Methode

<?php
class Foo
{
    function 
Variable()
    {
        
$name 'Bar';
        
$this->$name(); // Dies ruft die Bar() Methode auf
    
}

    function 
Bar()
    {
        echo 
"Das ist Bar";
    }
}

$foo = new Foo();
$funcname "Variable";
$foo->$funcname();   // Dies ruft $foo->Variable() auf

?>

Siehe auch call_user_func(), Variable Variablen und function_exists().



Interne (eingebaute) Funktionen

PHP enthält standmäßig viele Funktionen und Konstrukte, weiterhin gibt es viele Funktionen die vorausssetzen, dass bestimmte PHP-Extensions einkompiliert wurden, anderenfalls erhalten Sie beim Aufruf "undefined function"-Fehlermeldungen. Um z.B. Grafik-Funktionen wie imagecreatetruecolor() zu nutzen, müssen Sie PHP mit GD-Unterstützung kompilieren, oder um mysql_connect() zu nutzen, muss Ihr PHP mit MySQL-Unterstützung kompiliert sein. Viele Kernfunktionen wie z.B. die String- und Variablen-Funktionen sind bereits in jeder PHP-Version enthalten. Ein Aufruf von phpinfo() oder get_loaded_extensions() zeigt Ihnen, welche Extensions in Ihrer PHP-Installation verfügbar sind. Beachten Sie weiterhin, dass viele Extensions bereits standardmäßig aktiviert sind und das PHP-Manual nach Extensions unterteilt ist. Weitere Informationen zur Einrichtung von PHP finden Sie in den Kapiteln Konfiguration, Installation und den Kapiteln zu den einzelnen Extensions.

Wie Funktionsprototypen zu lesen und zu verstehen sind, ist im Kapitel 'Wie man eine Funktionsdefinition (Prototyp) liest' erklärt. Es ist wichtig zu erkennen, was eine Funktion zurückgibt und ob die übergebenen Parameter verändert werden. So gibt z.B. str_replace() den bearbeiteten String zurück, während usort() direkt auf der übergebenen Variablen arbeitet. Jede Handbuchseite enthält spezifische Informationen für jede Funktion wie ihre Parameter, die Rückgabewerte sowohl bei Erfolg als auch im Fehlerfall, Änderungen des Verhaltens und die Verfügbarkeit. Die Kenntnis dieser wichtigen (und oft subtilen) Unterschiede ist von entscheidender Bedeutung für das Schreiben korrekten PHP-Codes.

Hinweis: Wenn Funktionen andere Parameter erhalten als erwartet, d.h. wenn z.B. ein array übergeben wird obwohl ein string erwartet wird, so ist der Rückgabewert undefiniert. In solchen Fällen ist es üblich, dass NULL zurückgegeben wird, dies ist aber nur eine Konvention, auf die Sie sich nicht unbedingt verlassen können.

Siehe auch function_exists(), the function reference, get_extension_funcs() und dl().



Anonymous functions

Anonymous functions, also known as closures, allow the creation of functions which have no specified name. They are most useful as the value of callback parameters, but they have many other uses.

Beispiel #1 Anonymous function example

<?php
echo preg_replace_callback('~-([a-z])~', function ($match) {
    return 
strtoupper($match[1]);
}, 
'hello-world');
// outputs helloWorld
?>

Closures can also be used as the values of variables; PHP automatically converts such expressions into instances of the Closure internal class. Assigning a closure to a variable uses the same syntax as any other assignment, including the trailing semicolon:

Beispiel #2 Anonymous function variable assignment example

<?php
$greet 
= function($name)
{
    
printf("Hello %s\r\n"$name);
};

$greet('World');
$greet('PHP');
?>

Closures may also inherit variables from the parent scope. Any such variables must be declared in the function header. Inheriting variables from the parent scope is not the same as using global variables. Global variables exist in the global scope, which is the same no matter what function is executing. The parent scope of a closure is the function in which the closure was declared (not necessarily the function it was called from). See the following example:

Beispiel #3 Closures and scoping

<?php
// A basic shopping cart which contains a list of added products
// and the quantity of each product. Includes a method which
// calculates the total price of the items in the cart using a
// closure as a callback.
class Cart
{
    const 
PRICE_BUTTER  1.00;
    const 
PRICE_MILK    3.00;
    const 
PRICE_EGGS    6.95;

    protected   
$products = array();
    
    public function 
add($product$quantity)
    {
        
$this->products[$product] = $quantity;
    }
    
    public function 
getQuantity($product)
    {
        return isset(
$this->products[$product]) ? $this->products[$product] :
               
FALSE;
    }
    
    public function 
getTotal($tax)
    {
        
$total 0.00;
        
        
$callback =
            function (
$quantity$product) use ($tax, &$total)
            {
                
$pricePerItem constant(__CLASS__ "::PRICE_" .
                    
strtoupper($product));
                
$total += ($pricePerItem $quantity) * ($tax 1.0);
            };
        
        
array_walk($this->products$callback);
        return 
round($total2);;
    }
}

$my_cart = new Cart;

// Add some items to the cart
$my_cart->add('butter'1);
$my_cart->add('milk'3);
$my_cart->add('eggs'6);

// Print the total with a 5% sales tax.
print $my_cart->getTotal(0.05) . "\n";
// The result is 54.29
?>

Anonymous functions are currently implemented using the Closure class. This is an implementation detail and should not be relied upon.

Hinweis: Anonymous functions are available since PHP 5.3.0.

Hinweis: It is possible to use func_num_args(), func_get_arg(), and func_get_args() from within a closure.




Klassen und Objekte (PHP 5)

Inhaltsverzeichnis


Introduction

In PHP5 gibt es ein neues Objektmodell. Die Behandlung von Objekten durch PHP wurde vollständig neu geschrieben, was zu deutlich erhöhter Leistungsfähigkeit und mehr Fähigkeiten in diesem Bereich führte.

Tipp

Siehe auch Userland Naming Guide.



Die Grundlagen

class

Jede Klassendefinition beginnt mit dem Schlüsselwort class, gefolgt von einem Klassennamen, gefolgt von einem Paar geschweifter Klammern, die die Definitionen der Klasseneigenschaften und -methoden enthalten.

Der Klassenname kann jeder gültige Bezeichner sein, der kein von PHP PHP reserviertes Wort ist. Ein gültiger Klassenname beginnt mit einem Buchstaben oder einem Unterstrich, gefolgt von einer beliebigen Anzahl von Buchstaben, Ziffern oder Unterstrichen; als regulärer Ausdruck formuliert: [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*.

Eine Klasse darf aus ihren eigenen Konstanten, Variablen ("Eigenschaften" genannt) und Funktionen ("Methoden" genannt) bestehen.

Beispiel #1 Definition einer einfachen Klasse

<?php
class SimpleClass
{
    
// Deklaration einer Eigenschaft
    
public $var 'ein Standardwert';

    
// Deklaration einer Methode
    
public function displayVar() {
        echo 
$this->var;
    }
}
?>

Die Pseudovariable $this ist verfügbar, falls eine Methode aus einem Objektkontext heraus aufgerufen wird. $this ist eine Referenz auf das aufrufende Objekt (üblicherweise das Objekt, zu dem die Methode gehört, aber möglicherweise ein anderes Objekt, falls die Methode statisch aus dem Kontext eines zusätzlichen Objektes aufgerufen wird).

Beispiel #2 Einige Beispiele für die $this-Pseudovariable

<?php
class A
{
    function 
foo()
    {
        if (isset(
$this)) {
            echo 
'$this ist definiert (';
            echo 
get_class($this);
            echo 
")\n";
        } else {
            echo 
"\$this ist nicht definiert.\n";
        }
    }
}

class 
B
{
    function 
bar()
    {
        
// Hinweis: die folgende Zeile führt zu einer Warnung, wenn
        // E_STRICT aktiviert ist
        
A::foo();
    }
}

$a = new A();
$a->foo();

// Hinweis: die folgende Zeile führt zu einer Warnung, wenn E_STRICT aktiviert ist
A::foo();
$b = new B();
$b->bar();

// Hinweis: die folgende Zeile führt zu einer Warnung, wenn E_STRICT aktiviert ist
B::bar();
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

$this ist definiert (A)
$this ist nicht definiert.
$this ist definiert (B)
$this ist nicht definiert.

new

Um eine Instanz einer Klasse zu erzeugen, muss ein neues Objekt erzeugt und einer Variablen zugewiesen werden. Bei der Erzeugung wird das Objekt immer zugewiesen, außer wenn das Objekt einen definierten Konstruktor besitzt, der aufgrund eines Fehlers eine Exception wirft. Klassen sollten vor ihrer Instantiierung definiert werden (in manchen Fällen ist dies eine Notwendigkeit).

Beispiel #3 Eine Instanz erzeugen

<?php
$instanz 
= new SimpleClass();

// dies ist auch mit einer Variablen möglich:
$klassenname 'Foo';
$instanz = new $klassenname(); // Foo()
?>

Im Kontext einer Klasse ist es möglich, neue Objekte mit new self und new parent anzulegen.

Wenn man eine bereits erzeugte Instanz einer Klasse einer neuen Variablen zuweist, wird die neue Variable auf die selbe Instanz zugreifen wie das Objekt, das zugewiesen wurde. Dieses Verhalten ist das selbe, wenn man Instanzen an Funktionen übergibt. Eine Kopie eines bereits erzeugten Objektes erhält man, indem man es klont.

Beispiel #4 Objektzuweisung

<?php
$zugewiesen   
=  $instanz;
$referenz     =& $instanz;

$instanz->var '$zugewiesen wird diesen Wert haben';

$instanz null// $instanz und $referenz werden null

var_dump($instanz);
var_dump($referenz);
var_dump($zugewiesen);
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

NULL
NULL
object(SimpleClass)#1 (1) {
   ["var"]=>
     string(30) "$zugewiesen wird diesen Wert haben"
}

extends

Eine Klasse kann Methoden und Eigenschaften einer anderen Klasse erben, indem man das extends-Schlüsselwort in der Deklaration benutzt. Es ist nicht möglich, mehrere Klassen zu erweitern; eine Klasse kann nur eine einzige Basisklasse beerben.

Die geerbten Methoden und Eigenschaften können durch eine Neudeklaration mit dem gleichen Namen wie in der Elternklasse überschrieben werden. Falls die Elternklasse eine Methode als final definiert hat, kann diese Methode nicht überschrieben werden. Es ist möglich, auf die überschriebenen Methoden oder statischen Eigenschaften zuzugreifen, wenn diese mittels parent:: referenziert werden.

Beispiel #5 Einfache Vererbung

<?php
class ExtendClass extends SimpleClass
{
    
// Die Vatermethode überschreiben
    
function displayVar()
    {
        echo 
"Erweiternde Klasse\n";
        
parent::displayVar();
    }
}

$extended = new ExtendClass();
$extended->displayVar();
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

Erweiternde Klasse
ein Vorgabewert


Properties

Class member variables are called "properties". You may also see them referred to using other terms such as "attributes" or "fields", but for the purposes of this reference we will use "properties". They are defined by using one of the keywords public, protected, or private, followed by a normal variable declaration. This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.

See Sichtbarkeit for more information on the meanings of public, protected, and private.

Hinweis: In order to maintain backward compatibility with PHP 4, PHP 5 will still accept the use of the keyword var in property declarations instead of (or in addition to) public, protected, or private. However, var is no longer required. In versions of PHP from 5.0 to 5.1.3, the use of var was considered deprecated and would issue an E_STRICT warning, but since PHP 5.1.3 it is no longer deprecated and does not issue the warning.
If you declare a property using var instead of one of public, protected, or private, then PHP 5 will treat the property as if it had been declared as public.

Within class methods the properties, constants, and methods may be accessed by using the form $this->property (where property is the name of the property) unless the access is to a static property within the context of a static class method, in which case it is accessed using the form self::$property. See Static Keyword for more information.

The pseudo-variable $this is available inside any class method when that method is called from within an object context. $this is a reference to the calling object (usually the object to which the method belongs, but possibly another object, if the method is called statically from the context of a secondary object).

Beispiel #1 property declarations

<?php
class SimpleClass
{
   
// invalid property declarations:
   
public $var1 'hello ' 'world';
   public 
$var2 = <<<EOD
hello world
EOD;
   public 
$var3 1+2;
   public 
$var4 self::myStaticMethod();
   public 
$var5 $myVar;

   
// valid property declarations:
   
public $var6 myConstant;
   public 
$var7 = array(truefalse);

   
// This is allowed only in PHP 5.3.0 and later.
   
public $var8 = <<<'EOD'
hello world
EOD;
}
?>

Hinweis: There are some nice functions to handle classes and objects. You might want to take a look at the Class/Object Functions.

Unlike heredocs, nowdocs can be used in any static data context, including property declarations.

Beispiel #2 Example of using a nowdoc to initialize a property

<?php
class foo {
   
// As of PHP 5.3.0
   
public $bar = <<<'EOT'
bar
EOT;
}
?>

Hinweis: Nowdoc support was added in PHP 5.3.0.



Klassenkonstanten

Es ist möglich für jede Klasse konstante Werte zu definieren, die gleich und unabänderlich bleiben. Konstanten weichen darin von normalen Variablen ab, dass man nicht das $ Symbol benutzt, um sie zu deklarieren oder zu benutzen.

Der Wert kann nur ein konstanter Ausdruck sein, keine (zum Beispiel) Variablen, Klassenmamber, Ergebnisse einer mathematischen Operation oder Funktionsaufrufe.

Ein Interface kann ebenfalls constants enthalten. Die Interface-Dokumentation enthält Beispiele dazu.

Beginnend mit PHP 5.3.0 ist es möglich eine Variable als Klassenreferenz zu nutzen. Der Variablenwert kann kein Schlüsselwort (wie self, parent oder static) sein.

Beispiel #1 Eine Konstante definieren und benutzen

<?php
class MyClass
{
    const 
constant 'Konstanter Wert';

    function 
showConstant() {
        echo  
self::constant "\n";
    }
}

echo 
MyClass::constant "\n";

$classname "MyClass";
echo 
$classname::constant "\n"// Ab PHP 5.3.0

$class = new MyClass();
$class->showConstant();

echo 
$class::constant;  // Ab PHP 5.3.0
?>

Beispiel #2 Beispiel für statische Daten

<?php
class foo {
    
// Ab PHP 5.3.0
    
const bar = <<<'EOT'
bar
EOT;
}
?>

Nowdocs können, anders als heredocs, in jedem statischen Datenkontext verwendet werden.

Hinweis: Unterstützung von Nowdocs wurde in PHP 5.3.0 eingeführt.



Autoloading

Viele Entwickler, die objektorientierte Anwendungen entwickeln, erzeugen eine eigene PHP Quelldatei für jede Klassendefinition. Eines der größten Ärgernisse ist die Notwendigkeit, eine lange Liste von benötigten Include-Anweisungen am Anfang eines jeden Skripts (eine für jede Klasse).

In PHP 5 ist das nicht länger notwendig. Man kann eine __autoload Funktion definieren, die automatisch aufgerufen wird, falls man versucht eine noch nicht definierte Klasse oder ein nicht definiertes Interface zu benutzen. Durch den Aufruf dieser Funktion erhält die Scripting Engine einen letzten Versuch, die Klasse zu laden, bevor PHP unter Ausgabe einer Fehlermeldung scheitert.

Hinweis: Exceptions, die in einer __autoload Funktion geworfen werden, sind nicht in einem Catch-Block fangbar und führen zu einem fatalen Fehler.

Hinweis: Autoloading ist nicht verfügbar, wenn man PHP im CLI interaktiven Modus betreibt.

Hinweis: Wird der Klassenname z.B. an die Funktion call_user_func() ist zu beachten das er gefährliche Zeichen wie z.B. ../ enthalten kann. Es wird daher empfohlen keine Benutzereingaben an solche Funktionen weiterzugeben oder zumindest die Eingaben in der __autoload() zu prüfen.

Beispiel #1 Autoload Beispiel

Dieses Beispiel versucht die Klassen MyClass1 und MyClass2 aus den entsprechenden Dateien MyClass1.php und MyClass2.php zu laden.

<?php
function __autoload($class_name) {
    require_once 
$class_name '.php';
}

$obj  = new MyClass1();
$obj2 = new MyClass2(); 
?>

Beispiel #2 Weiteres Autoload Beispiel

Dieses Beispiel versucht das Interface ITest zu laden.

<?php

function __autoload($name) {
    
var_dump($name);
}

class 
Foo implements ITest {
}
 
/*
string(5) "ITest"
 
Fatal error: Interface 'ITest' not found in ...
*/
?>



Konstruktoren und Destruktoren

Konstruktor

void __construct ([ mixed $args [, $... ]] )

PHP 5 erlaubt es Entwicklern, Konstruktormethoden für Klassen zu deklarieren. Klassen mit Konstruktormethoden rufen diese für jedes neu erzeugte Objekt auf, so dass Konstruktoren für alle Initialisierungen passend sind, die das Objekt brauchen könnte bevor es benutzt wird.

Hinweis: Konstruktoren von Vaterklassen werden nicht implizit aufgerufen, wenn die Kindklasse einen Konstruktor definiert. Um einen Vaterkonstruktor zu benutzen ist ein Aufruf von parent::__construct() innerhalb des Kindkonstruktors notwendig.

Beispiel #1 Die neuen, vereinheitlichten Konstruktoren verwenden

<?php
class BaseClass {
   function 
__construct() {
       print 
"Im BaseClass Konstruktor\n";
   }
}

class 
SubClass extends BaseClass {
   function 
__construct() {
       
parent::__construct();
       print 
"Im SubClass Konstruktor\n";
   }
}

$obj = new BaseClass();
$obj = new SubClass();
?>

Für die Abwärtskompatibilität sucht PHP 5 nach einer Konstruktorfunktion nach dem alten Stil mit dem Namen der Klasse, falls es keine __construct() Funktion für eine Klasse findet. Effektiv bedeutet das, dass der einzige Fall mit Kompatibilitätsproblemen derjenige einer Klasse mit dem Namen __construct() ist, welche für andere Zwecke benutzt wird.

Destruktor

void __destruct ( void )

PHP 5 führt ein Destruktorkonzept ähnlich dem anderer objektorientierter Programmiersprachen wie C++ ein. Die Destruktormethode wird aufgerufen, sobald alle Referenzen auf ein bestimmtes Objekt entfernt werden oder wenn das Objekt explizit zerstört wird, oder in beliebiger Reihenfolge am Ende des Skripts.

Beispiel #2 Destruktor Beispiel

<?php
class MyDestructableClass {
   function 
__construct() {
       print 
"Im Konstruktor\n";
       
$this->name "MyDestructableClass";
   }

   function 
__destruct() {
       print 
"Zerstoere " $this->name "\n";
   }
}

$obj = new MyDestructableClass();
?>

Wie Konstruktoren auch, werden Vaterdestruktoren nicht implizit durch die Engine aufgerufen. Um einen Vaterdestruktor zu benutzen muss man explizit die Funktion parent::__destruct() in der Destruktorimplementierung aufrufen

Hinweis: Der Destruktor wird während der Skript Abschaltung aufgerufen, weshalb die Header immer bereits gesendet sind. Das aktuelle Verzeichnis während der Beendigungsphase des Skripts kann bei einigen SAPIs (z.B. Apache) ein anderes sein.

Hinweis: Der Versucht eine Exception aus einem Destruktor (der in der Beendigungsphase des Skripts aufgerufen wurde) heraus zu werfen wird einen fatalen Fehler auslösen.



Sichtbarkeit

Die Sichtbarkeit einer Eigenschaft oder Methode kann definiert werden, indem man der Deklaration eines der Schlüsselwörter public, protected oder private voranstellt. Auf public deklarierte Elemente kann von überall her zugegriffen werden. Protected beschränkt den Zugang auf Vaterklassen und abgeleitete Klassen (sowie die Klasse die das Element definiert). Private grenzt die Sichtbarkeit einzig auf die Klasse ein, die das Element definiert.

Sichtbarkeit von Membern

Klassenmember müssen mitteld public, private oder protected definiert werden.

Beispiel #1 Memberdeklaration

<?php
/**
 * Definiere MyClass
 */
class MyClass
{
    public 
$public 'Public';
    protected 
$protected 'Protected';
    private 
$private 'Private';

    function 
printHello()
    {
        echo 
$this->public;
        echo 
$this->protected;
        echo 
$this->private;
    }
}

$obj = new MyClass();
echo 
$obj->public// Funktioniert
echo $obj->protected// Fataler Fehler
echo $obj->private// Fataler Fehler
$obj->printHello(); // Zeigt Public, Protected und Private


/**
 * Definiere MyClass2
 */
class MyClass2 extends MyClass
{
    
// Wir können die public und protected Methoden neu deklarieren, 
    // aber nicht private
    
protected $protected 'Protected2';

    function 
printHello()
    {
        echo 
$this->public;
        echo 
$this->protected;
        echo 
$this->private;
    }
}

$obj2 = new MyClass2();
echo 
$obj2->public// Funktioniert
echo $obj2->private// Undefiniert
echo $obj2->protected// Fataler Fehler
$obj2->printHello(); // Zeigt Public, Protected2, Undefined

?>

Hinweis: Die PHP 4 Methode, Variablen mit dem Schlüsselwort var zu deklarieren, ist aus Gründen der Abswärtskompatibilität weiterhin unterstützt (als Synonym für das public-Schlüsselwort). In PHP 5 vor 5.1.3 hat dessen Verwendung eine E_STRICT-Warnung hervorgerufen.

Sichtbarkeit von Methoden

Klassenmethoden müssen mit public, private oder protected definiert werden. Methoden ohne jede Deklaration sind als public definiert.

Beispiel #2 Methodendeklaration

<?php
/**
 * Definiere MyClass
 */
class MyClass
{
    
// Deklariert einen public Konstruktor
    
public function __construct() { }

    
// Deklariere eine public Funktion
    
public function MyPublic() { }

    
// Deklariere eine protected Funktion
    
protected function MyProtected() { }

    
// Deklariere eine private Funktion
    
private function MyPrivate() { }

    
// Dies ist public
    
function Foo()
    {
        
$this->MyPublic();
        
$this->MyProtected();
        
$this->MyPrivate();
    }
}

$myclass = new MyClass;
$myclass->MyPublic(); // Funktioniert
$myclass->MyProtected(); // Fataler Fehler
$myclass->MyPrivate(); // Fataler Fehler
$myclass->Foo(); // Public, Protected und Private funktionieren


/**
 * Definiere MyClass2
 */
class MyClass2 extends MyClass
{
    
// Dies ist public
    
function Foo2()
    {
        
$this->MyPublic();
        
$this->MyProtected();
        
$this->MyPrivate(); // Fataler Fehler
    
}
}

$myclass2 = new MyClass2;
$myclass2->MyPublic(); // Funktioniert
$myclass2->Foo2(); // Public und Protected funktionieren, Private nicht

class Bar 
{
    public function 
test() {
        
$this->testPrivate();
        
$this->testPublic();
    }

    public function 
testPublic() {
        echo 
"Bar::testPublic\n";
    }
    
    private function 
testPrivate() {
        echo 
"Bar::testPrivate\n";
    }
}

class 
Foo extends Bar 
{
    public function 
testPublic() {
        echo 
"Foo::testPublic\n";
    }
    
    private function 
testPrivate() {
        echo 
"Foo::testPrivate\n";
    }
}

$myFoo = new foo();
$myFoo->test(); // Bar::testPrivate 
                // Foo::testPublic
?>



Object Inheritance

Inheritance is a well-esablished programming principle, and PHP makes use of this principle in its object model. This principle will affect the way many classes and objects relate to one another.

For example, when you extend a class, the subclass inherits all of the public and protected methods from the parent class. Unless a class overrides those methods, they will retain their original functionality.

This is useful for defining and abstracting functionality, and permits the implementation of additional functionality in similar objects without the need to reimplement all of the shared functionality.

Beispiel #1 Inheritance Example

<?php

class foo
{
    public function 
printItem($string)
    {
        echo 
'Foo: ' $string PHP_EOL;
    }
    
    public function 
printPHP()
    {
        echo 
'PHP is great.' PHP_EOL;
    }
}

class 
bar extends foo
{
    public function 
printItem($string)
    {
        echo 
'Bar: ' $string PHP_EOL;
    }
}

$foo = new foo();
$bar = new bar();
$foo->printItem('baz'); // Output: 'Foo: baz'
$foo->printPHP();       // Output: 'PHP is great' 
$bar->printItem('baz'); // Output: 'Bar: baz'
$bar->printPHP();       // Output: 'PHP is great'

?>


Gültigkeitsbereichsoperator (::)

Der Gültigkeitsbereichsoperator (auch Paamayim Nekudotayim genannt) oder in einfacheren Worten der Doppel-Doppelpunkt ist ein Kürzel, das Zugriff auf statische, konstante und überschriebene Member oder Methoden einer Klasse erlaubt.

Wenn Sie diese Elemente außerhalb der Klassendefinition ansprechen, benutzen Sie den Namen der Klasse.

Beginnend mit PHP 5.3.0 ist es möglich eine Variable als Klassenreferenz zu nutzen. Der Variablenwert kann kein Schlüsselwort (wie self, parent oder static) sein.

Paamayim Nekudotayim scheint auf den ersten Blick eine eigenartige Wahl für die Benennung eines Doppel-Doppelpunktes zu sein. Jedoch entschied sich das Zend Team ihn so zu nennen, während Sie die Zend Engine 0.5 schrieben (welche PHP 3 antreibt). Tatsächlich bedeutet das Doppel-Doppelpunkt - in Hebräisch.

Beispiel #1 :: außerhalb der Klassendefinition

<?php
class MyClass {
    const 
CONST_VALUE 'Ein konstanter Wert';
}

$classname 'MyClass';
echo 
$classname::CONST_VALUE// Ab PHP 5.3.0

echo MyClass::CONST_VALUE;
?>

Die zwei speziellen Schlüsselwörter self und parent werden benutzt, um auf Member und Methoden von innerhalb der Klassendefinition zuzugreifen.

Beispiel #2 :: innerhalb der Klassendefinition

<?php
class OtherClass extends MyClass
{
    public static 
$my_static 'statische var';

    public static function 
doubleColon() {
        echo 
parent::CONST_VALUE "\n";
        echo 
self::$my_static "\n";
    }
}

$classname 'OtherClass';
echo 
$classname::doubleColon(); // Ab PHP 5.3.0

OtherClass::doubleColon();
?>

Wenn eine abgeleitete Klasse die Definition der Methode eines Vaters überschreibt, wird PHP die Methode des Vaters nicht aufrufen. Es obliegt der abgeleiteten Klasse, ob die Methode der Vaterklasse augerufen wird oder nicht. Dies gilt ebenfalls für Konstruktoren und Destruktoren, Überladung und magische Methodendefinitionen.

Beispiel #3 Eine Vatermethode aufrufen

<?php
class MyClass
{
    protected function 
myFunc() {
        echo 
"MyClass::myFunc()\n";
    }
}

class 
OtherClass extends MyClass
{
    
// Die Definition des Vaters überschreiben
    
public function myFunc()
    {
        
// Aber dennoch die Funktion des Vaters aufrufen
        
parent::myFunc();
        echo 
"OtherClass::myFunc()\n";
    }
}

$class = new OtherClass();
$class->myFunc();
?>


Static Schlüsselwort

Klassenmember oder -methoden als statisch zu deklarieren macht diese zugänglich, ohne dass man die Klasse instantiieren muss. Auf ein als statisch deklariertes Member kann nicht mit einem instantiierten Klassenobjekt zugegriffen werden (obgleich eine statische Methode dies kann).

Für die Abwärtskompatibilität zu PHP 4 werden Member oder Methode behandelt als ob diese als public static deklariert wären, wenn keine Sichtbarkeit deklariert wird.

Als Initialwerte für statische Eigenschaften können nur Zeichenketten und Konstanten zugewiesen werden, die Zuweisung berechneter Ausdrücke ist nicht möglich. Während also die Initialisierung mit einem Integer oder Array möglich ist können der Wert einer anderen Variablen, der Rückgabewert einer Funktion oder ein Objekt nicht als Initialwert zugewiesen werden.

Weil statische Methoden ohne die Instanz eines erzeugten Objektes aufrufbar sind, ist die Pseudovariable $this nicht innerhalb von der als statisch deklarierten Methode verfügbar.

Auf statische Eigenschaften kann nicht durch das Objekt mittels des Pfeiloperators -> zugegriffen werden.

Unstatische Methoden statisch aufzurufen ruft eine Warnung der Stufe E_STRICT hervor.

Beginnend mit PHP 5.3.0 kann die Klasse über eine Variable referenziert werden. Der Variablenwert kann dabei kein Schlüsselwort (wie self, parent oder static) sein.

Beispiel #1 Beispiel für statische Member

<?php
class Foo
{
    public static 
$my_static 'foo';

    public function 
staticValue() {
        return 
self::$my_static;
    }
}

class 
Bar extends Foo
{
    public function 
fooStatic() {
        return 
parent::$my_static;
    }
}


print 
Foo::$my_static "\n";

$foo = new Foo();
print 
$foo->staticValue() . "\n";
print 
$foo->my_static "\n";      // Undefinierte "Eigenschaft" my_static 

print $foo::$my_static "\n";
$classname 'Foo';
print 
$classname::$my_static "\n";

print 
Bar::$my_static "\n";
$bar = new Bar();
print 
$bar->fooStatic() . "\n";
?>

Beispiel #2 Beispiel für statische Methoden

<?php
class Foo {
    public static function 
aStaticMethod() {
        
// ...
    
}
}

Foo::aStaticMethod();
$classname 'Foo';
$classname::aStaticMethod();
?>


Klassenabstraktion

PHP 5 führt abstrakte Klassen und Methoden ein. Es ist nicht erlaubt, eine Instanz einer Klasse zu erzeugen, die abstrakt definiert wurde. Jede Klasse, die wenigstens eine abstrakte Methode enthält, muss ebenso abstrakt sein. Abstrakt definierte Methoden deklarieren einfach die Signatur der Methode, sie dürfen nicht die Implementierung definieren.

Wenn eine abstrakte Klasse abgeleitet wird, müssen alle in der Deklaration der Vaterklasse abstrakt bezeichneten Methoden durch das Kind definiert werden. Zusätzlich müssen diese Methoden mit der selben (oder einer weniger einschränkenden) Sichtbarkeit definiert werden. Wenn die abstrakte Methode zum Beispiel als protected definiert ist, muss die Funktionsimplementierung entweder als protected oder public, aber nicht private, definiert sein.

Beispiel #1 Beispiel für abstrakte Klasse

<?php
abstract class AbstractClass
{
    
// Die abgeleitete Klasse zwingen, diese Methoden zu definieren
    
abstract protected function getValue();
    abstract protected function 
prefixValue($prefix);

    
// Gemeinsame Methode
    
public function printOut() {
        print 
$this->getValue() . "\n";
    }
}

class 
ConcreteClass1 extends AbstractClass
{
    protected function 
getValue() {
        return 
"ConcreteClass1";
    }

    public function 
prefixValue($prefix) {
        return 
"{$prefix}ConcreteClass1";
    }
}

class 
ConcreteClass2 extends AbstractClass
{
    public function 
getValue() {
        return 
"ConcreteClass2";
    }
    
    public function 
prefixValue($prefix) {
        return 
"{$prefix}ConcreteClass2";
    }
}

$class1 = new ConcreteClass1;
$class1->printOut();
echo 
$class1->prefixValue('FOO_') ."\n";

$class2 = new ConcreteClass2;
$class2->printOut();
echo 
$class2->prefixValue('FOO_') ."\n";
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

ConcreteClass1
FOO_ConcreteClass1
ConcreteClass2
FOO_ConcreteClass2

Bestehender Code, der keine benutzerdefinierten Klassen oder Funktionen mit dem Namen 'abstract' besitzt, sollte ohne Änderungen lauffähig sein.



Interfaces

Interfaces erlauben die Erzeugung von Code, der spezifiziert, welche Methoden eine Klasse implementieren muss, ohne definieren zu müssen, wie diese Methoden behandelt werden.

Interfaces werden mit dem interface Schlüsselwort auf die selbe Weise wie eine Standardklasse definiert, ohne dass eine der Methoden ihren Inhalt definiert.

Alle in einem Interface deklarierten Methoden müssen public sein, dies liegt in der Natur eines Interfaces.

implements

Um ein Interface zu implementieren, wird der implements-Operator benutzt. Alle Methoden des Interfaces müssen innerhalb der Klasse implementiert werden; Unterlassung wird zu einem fatalen Fehler führen. Klassen dürfen, falls dies gewünscht wird, mehr als ein Interface implementieren, indem man die Interfaces voneinander mit einem Komma abtrennt.

Hinweis: Eine Klasse kann nicht zwei Interfaces, die sich identische Funktionsnamen teilen, implementieren, da dies zu Doppeldeutigkeiten führen würde.

Hinweis: Ein Interface kann ebenso wie eine Klasse mit Hilfe des Schlüsselwortes extend erweitert werden.

Konstanten

Ein Interface kann Konstanten definieren. Interface-Konstanten funktionieren genauso wie Klassenkonstanten. Eine Interfacekonstante kann von anderen Interfaces oder Klassen, die von diesem Interface erben, nicht verändert werden.

Beispiele

Beispiel #1 Interface-Beispiel

<?php
// Deklariere das Interface 'iTemplate'
interface iTemplate
{
    public function 
setVariable($name$var);
    public function 
getHtml($template);
}

// Implementiere das Interface
// Dies funktioniert
class Template implements iTemplate
{
    private 
$vars = array();
  
    public function 
setVariable($name$var)
    {
        
$this->vars[$name] = $var;
    }
  
    public function 
getHtml($template)
    {
        foreach(
$this->vars as $name => $value) {
            
$template str_replace('{' $name '}'$value$template);
        }
 
        return 
$template;
    }
}

// Dies wird nicht funktionieren
// Fatal error: Class BadTemplate contains 1 abstract methods
// and must therefore be declared abstract (iTemplate::getHtml)
class BadTemplate implements iTemplate
{
    private 
$vars = array();
  
    public function 
setVariable($name$var)
    {
        
$this->vars[$name] = $var;
    }
}

?>

Beispiel #2 Interface-Vererbung

<?php
interface a

public function foo();


interface 
extends a
{
  public function 
baz(Baz $baz);
}

// Dies Funktioniert 
class implements b
{
  public function 
foo()
  {
  }

  public function 
baz(Baz $baz)
  {
  }
}

// Dies funktioniert nicht und führt zu einem fatalen Fehler
class implements b
{
  public function 
foo()
  {
  }

  public function 
baz(Foo $foo)
  {
  }
}
?>

Beispiel #3 Interface-Mehrfachvererbung

<?php
interface a
{
  public function 
foo();
}
    
interface 
b
{
  public function 
bar();
}
    
interface 
extends ab
{
  public function 
baz();
}
    
class 
implements c
{
  public function 
foo()
  {
  }
    
  public function 
bar()
  {
  }
    
  public function 
baz()
  {
  }
}
?>

Beispiel #4 Interfaces mit Konstanten

<?php
interface a
{
  const 
'Interface constant';
}
    
// Ausgabe: Interface constant
echo a::b;
    
// Der folgende Abschnitt wird nicht funktionieren, da
// ein Überschreiben der Konstanten nicht gestattet ist.
// Dies ist das gleiche Konzept wie bei Klassenkonstanten.
class implements a
{
  const 
'Class constant';
}
?>

Siehe auch den instanceof-Operator.



Overloading

Overloading in PHP provides means to dynamically "create" properties and methods. These dynamic entities are processed via magic methods one can establish in a class for various action types.

The overloading methods are invoked when interacting with properties or methods that have not been declared or are not visible in the current scope. The rest of this section will use the terms "inaccessible properties" and "inaccessible methods" to refer to this combination of declaration and visibility.

All overloading methods must be defined as public.

Hinweis: None of the arguments of these magic methods can be passed by reference.

Hinweis: PHP's interpretation of "overloading" is different than most object oriented languages. Overloading traditionally provides the ability to have multiple methods with the same name but different quantities and types of arguments.

Changelog

Version Beschreibung
5.3.0 Added __callStatic(). Added warning to enforce public visibility and non-static declaration.
5.1.0 Added __isset() and __unset().

Property overloading

void __set ( string $name , mixed $value )
mixed __get ( string $name )
bool __isset ( string $name )
void __unset ( string $name )

__set() is run when writing data to inaccessible properties.

__get() is utilized for reading data from inaccessible properties.

__isset() is triggered by calling isset() or empty() on inaccessible properties.

__unset() is invoked when unset() is used on inaccessible properties.

The $name argument is the name of the property being interacted with. The __set() method's $value argument specifies the value the $name'ed property should be set to.

Property overloading only works in object context. These magic methods will not be triggered in static context. Therefore these methods can not be declared static.

Hinweis: The return value of __set() is ignored because of the way PHP processes the assignment operator. Similarly, __get() is never called when chaining assignemnts together like this:

 $a = $obj->b = 8; 

Beispiel #1 Overloading properties via the __get(), __set(), __isset() and __unset() methods

<?php
class PropertyTest {
    
/**  Location for overloaded data.  */
    
private $data = array();

    
/**  Overloading not used on declared properties.  */
    
public $declared 1;

    
/**  Overloading only used on this when accessed outside the class.  */
    
private $hidden 2;

    public function 
__set($name$value) {
        echo 
"Setting '$name' to '$value'\n";
        
$this->data[$name] = $value;
    }

    public function 
__get($name) {
        echo 
"Getting '$name'\n";
        if (
array_key_exists($name$this->data)) {
            return 
$this->data[$name];
        }

        
$trace debug_backtrace();
        
trigger_error(
            
'Undefined property via __get(): ' $name .
            
' in ' $trace[0]['file'] .
            
' on line ' $trace[0]['line'],
            
E_USER_NOTICE);
        return 
null;
    }

    
/**  As of PHP 5.1.0  */
    
public function __isset($name) {
        echo 
"Is '$name' set?\n";
        return isset(
$this->data[$name]);
    }

    
/**  As of PHP 5.1.0  */
    
public function __unset($name) {
        echo 
"Unsetting '$name'\n";
        unset(
$this->data[$name]);
    }

    
/**  Not a magic method, just here for example.  */
    
public function getHidden() {
        return 
$this->hidden;
    }
}


echo 
"<pre>\n";

$obj = new PropertyTest;

$obj->1;
echo 
$obj->"\n\n";

var_dump(isset($obj->a));
unset(
$obj->a);
var_dump(isset($obj->a));
echo 
"\n";

echo 
$obj->declared "\n\n";

echo 
"Let's experiment with the private property named 'hidden':\n";
echo 
"Privates are visible inside the class, so __get() not used...\n";
echo 
$obj->getHidden() . "\n";
echo 
"Privates not visible outside of class, so __get() is used...\n";
echo 
$obj->hidden "\n";
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

Setting 'a' to '1'
Getting 'a'
1

Is 'a' set?
bool(true)
Unsetting 'a'
Is 'a' set?
bool(false)

1

Let's experiment with the private property named 'hidden':
Privates are visible inside the class, so __get() not used...
2
Privates not visible outside of class, so __get() is used...
Getting 'hidden'


Notice:  Undefined property via __get(): hidden in <file> on line 70 in <file> on line 29

Method overloading

mixed __call ( string $name , array $arguments )
mixed __callStatic ( string $name , array $arguments )

__call() is triggered when invoking inaccessible methods in an object context.

__callStatic() is triggered when invoking inaccessible methods in a static context.

The $name argument is the name of the method being called. The $arguments argument is an enumerated array containing the parameters passed to the $name'ed method.

Beispiel #2 Overloading methods via the __call() and __callStatic() methods

<?php
class MethodTest {
    public function 
__call($name$arguments) {
        
// Note: value of $name is case sensitive.
        
echo "Calling object method '$name' "
             
implode(', '$arguments). "\n";
    }

    
/**  As of PHP 5.3.0  */
    
public static function __callStatic($name$arguments) {
        
// Note: value of $name is case sensitive.
        
echo "Calling static method '$name' "
             
implode(', '$arguments). "\n";
    }
}

$obj = new MethodTest;
$obj->runTest('in object context');

MethodTest::runTest('in static context');  // As of PHP 5.3.0
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

Calling object method 'runTest' in object context
Calling static method 'runTest' in static context


Objektiteration

PHP 5 bietet eine Möglichkeit, Objekte so zu definieren, dass es möglich ist, eine Liste von Elementen zu durchlaufen, z.B. mit dem foreach Schlüsselwort. Standardmäßig werden alle sichtbaren Eigenschaften für die Iteration benutzt.

Beispiel #1 Einfache Objektiteration

<?php
class MyClass
{
    public 
$var1 'Wert 1';
    public 
$var2 'Wert 2';
    public 
$var3 'Wert 3';

    protected 
$protected 'protected var';
    private   
$private   'private var';

    function 
iterateVisible() {
       echo 
"MyClass::iterateVisible:\n";
       foreach(
$this as $key => $value) {
           print 
"$key => $value\n";
       }
    }
}

$class = new MyClass();

foreach(
$class as $key => $value) {
    print 
"$key => $value\n";
}
echo 
"\n";


$class->iterateVisible();

?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

var1 => Wert 1
var2 => Wert 2
var3 => Wert 3

MyClass::iterateVisible:
var1 => Wert 1
var2 => Wert 2
var3 => Wert 3
protected => protected var
private => private var

Wie die Ausgabe zeigt, lief das foreach über alle sichtbaren Variablen, auf die zugegriffen werden kann. Um es einen Schritt weiter zu treiben, kann man eines der PHP 5 internen Interfaces, nämlich Iterator, implementieren. Das erlaubt dem Objekt zu entscheiden was und wie das Objekt iteriert wird.

Beispiel #2 Objektiteration mit implementiertem Iterator

<?php
class MyIterator implements Iterator
{
    private 
$var = array();

    public function 
__construct($array)
    {
        if (
is_array($array)) {
            
$this->var $array;
        }
    }

    public function 
rewind() {
        echo 
"zurückspulen\n";
        
reset($this->var);
    }

    public function 
current() {
        
$var current($this->var);
        echo 
"aktuell: $var\n";
        return 
$var;
    }

    public function 
key() {
        
$var key($this->var);
        echo 
"key: $var\n";
        return 
$var;
    }

    public function 
next() {
        
$var next($this->var);
        echo 
"nächstes: $var\n";
        return 
$var;
    }

    public function 
valid() {
        
$var $this->current() !== false;
        echo 
"gültig: {$var}\n";
        return 
$var;
    }
}

$values = array(1,2,3);
$it = new MyIterator($values);

foreach (
$it as $a => $b) {
    print 
"$a$b\n";
}
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

zurückspulen
aktuell: 1
gültig: 1
aktuell: 1
key: 0
0: 1
nächstes: 2
aktuell: 2
gültig: 1
aktuell: 2
key: 1
1: 2
nächstes: 3
aktuell: 3
gültig: 1
aktuell: 3
key: 2
2: 3
nächstes:
aktuell:
gültig:

Man kann eine Klasse ebenfalls so definieren, dass diese nicht alle Funktionen von Iterator definieren muss, indem man einfach das PHP 5 IteratorAggregate Interface implementiert.

Beispiel #3 Objektiteration mit implementiertem IteratorAggregate

<?php
class MyCollection implements IteratorAggregate
{
    private 
$items = array();
    private 
$count 0;

    
// benötigte Funktion des IteratorAggregate Interface
    
public function getIterator() {
        return new 
MyIterator($this->items);
    }

    public function 
add($value) {
        
$this->items[$this->count++] = $value;
    }
}

$coll = new MyCollection();
$coll->add('Wert 1');
$coll->add('Wert 2');
$coll->add('Wert 3');

foreach (
$coll as $key => $val) {
    echo 
"key/value: [$key -> $val]\n\n";
}
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

zurückspulen
aktuell: Wert 1
gültig: 1
aktuell: Wert 1
key: 0
key/value: [0 -> Wert 1]

nächstes: Wert 2
aktuell: Wert 2
gültig: 1
aktuell: Wert 2
key: 1
key/value: [1 -> Wert 2]

nächstes: Wert 3
aktuell: Wert 3
gültig: 1
aktuell: Wert 3
key: 2
key/value: [2 -> Wert 3]

nächstes:
aktuell:
gültig:

Hinweis: Für mehr Beispiele für die Benutzung von Iteratoren siehe auch SPL Erweiterung.



Pattern

Pattern sind eine Möglichkeit, um optimale Verfahren und gute Entwürfe zu beschreiben. Sie zeigen eine flexible Lösung für verbreitete Programierprobleme.

Factory

Das Factory Pattern erlaubt die Instantiierung von Objekten zur Laufzeit. Es wird Factory Pattern genannt, weil es für die Herstellung eines Objektes zuständig ist. Eine parametrisierte Factory bekommt den Namen der zu instantiierenden Klasse als Parameter übergeben.

Beispiel #1 Parametrisierte Factorymethode

<?php
class Example
{
    
// Die parametrisierte Factorymethode
    
public static function factory($type)
    {
        if (include_once 
'Treiber/' $type '.php') {
            
$classname 'Treiber_' $type;
            return new 
$classname;
        } else {
            throw new 
Exception ('Treiber nicht gefunden');
        }
    }
}
?>

Wenn diese Methode in einer Klasse definiert wird, erlaubt sie dieser, Treiber bei Bedarf zu laden. Wenn die Beispiel Klasse eine Datenbankabstraktionsklasse wäre, könnte das Laden eines MySQL und SQLite Treibers wie folgt aussehen:

<?php
// Lade den MySQL Treiber
$mysql Beispiel::factory('MySQL');

// Lade den SQLite Treiber
$sqlite Beispiel::factory('SQLite');
?>

Singleton

Das Singleton Pattern greift in Situationen, in denen es nur eine Instanz einer Klasse geben darf. Das gebräuchlichste Beispiel ist eine Datenbankverbindung. Die Implementierung dieses Musters erlaubt dem Programmierer diese einzige Instanz leicht für viele andere Objekte zugänglich zu machen.

Beispiel #2 Singleton Funktion

<?php
class Beispiel
{
    
// Speichert die Instanz der Klasse
    
private static $instance;
    
    
// Ein private Konstruktor; verhindert die direkte Erzeugung des Objektes
    
private function __construct() 
    {
        echo 
'Ich bin hergestellt';
    }

    
// Die Singleton Funktion
    
public static function singleton() 
    {
        if (!isset(
self::$instance)) {
            
$c __CLASS__;
            
self::$instance = new $c;
        }

        return 
self::$instance;
    }
    
    
// Beispielmethode
    
public function bellen()
    {
        echo 
'Wuff!';
    }

    
// Halte Benutzer vom Klonen der Instanz ab
    
public function __clone()
    {
        
trigger_error('Klonen ist nicht erlaubt.'E_USER_ERROR);
    }

}

?>

Dies erlaubt das Abrufen einer einzigen Instanz der Beispiel Klasse.

<?php
// Das wird fehlschlagen, weil der Kosntruktor private ist
$test = new Beispiel

// Das wird immer eine einzige Instanz der Klasse abrufen
$test Beispiel::singleton();
$test->bellen();

// Das wird einen E_USER_ERROR ausgeben
$test_clone = clone $test;

?>


Magische Methoden

Die Funktionen __construct, __destruct, __call, __callStatic, __get, __set, __isset, __unset, __sleep, __wakeup, __toString, __invoke, __set_state und __clone sind in PHP-Klassen magisch. Man kann keine Funktionen gleichen Namens in einer seiner Klassen haben, wenn man nicht die magische Funktionalität, die sie mit sich bringen, haben will.

Achtung

PHP reserviert alle Funktionsnamen, die mit __ beginnen, als magisch. Es wird empfohlen, keine Funktionsnamen mit __ in PHP zu benutzen, es sei denn, man möchte dokumentierte magische Funktionalität verwenden.

__sleep und __wakeup

serialize() prüft, ob Ihre Klasse eine Funktion mit dem magischen Namen __sleep besitzt. Wenn dem so ist, wird die Funktion vor jeder Serialisierung ausgeführt. Sie kann das Objekt aufräumen und es wird von ihr erwartet, dass sie ein Array mit den Namen aller Variablen zurückliefert, die serialisiert werden sollen. Wenn die Methode nichts zurückgibt, so wird NULL serialisiert und eine E_NOTICE ausgegeben.

Die beabsichtigte Verwendung von __sleep ist, nicht gespeicherte Daten zu sichern oder ähnliche Aufräumarbeiten zu erledigen. Die Funktion ist ebenfalls nützlich, wenn Sie sehr große Objekte haben, welche nicht komplett gespeichert werden müssen.

Umgekehrt überprüft unserialize() die Anwesenheit einer Funktion mit dem magischen Namen __wakeup. Falls vorhanden, kann diese Funktion alle Ressourcen, die das Objekt haben könnte, wiederherstellen.

Der beabsichtigte Zweck von __wakeup ist es, alle Datenbankverbindungen wiederherzustellen, die während der Serialisierung verloren gegangen sein könnten, oder auch andere Aufgaben zur erneuten Initialisierung.

Beispiel #1 Sleep- und Wakeup-Beispiel

<?php
class Connection {
    protected 
$link;
    private 
$server$username$password$db;

    public function 
__construct($server$username$password$db)
    {
        
$this->server $server;
        
$this->username $username;
        
$this->password $password;
        
$this->db $db;
        
$this->connect();
    }

    private function 
connect()
    {
        
$this->link mysql_connect($this->server$this->username$this->password);
        
mysql_select_db($this->db$this->link);
    }

    public function 
__sleep()
    {
        return array(
'server''username''password''db');
    }

    public function 
__wakeup()
    {
        
$this->connect();
    }
}
?>

__toString

Die __toString-Methode erlaubt einer Klasse zu entscheiden, wie sie reagieren will, wenn sie in eine Zeichenkette umgewandelt wird.

Beispiel #2 Einfaches Beispiel

<?php
// Deklariere eine einfache Klasse
class TestClass
{
    public 
$foo;

    public function 
__construct($foo) {
        
$this->foo $foo;
    }

    public function 
__toString() {
        return 
$this->foo;
    }
}

$class = new TestClass('Hallo');
echo 
$class;
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

Hallo

Es muss angemerkt werden, dass die __toString-Methode in Versionen vor PHP 5.2.0 nur in direkter Kombination mit echo() oder print() aufgerufen wurde. Beginnend mit PHP 5.2.0 erfolgt dieser Aufruf in jedem Stringkontext (z.B. in printf() mit %s-Platzhalter), aber in keinem der anderen Typenkontexte (z.B. mit dem %d-Platzhalter). Ebenfalls beginnend mit PHP 5.2.0 bewirkt die Umwandlung eines Objekts ohne __toString-Methode in einen String einen Fehler der Klasse E_RECOVERABLE_ERROR.

__invoke

Die __invole-Methode wird aufgerufen, wenn ein Skript versucht, ein Objekt als Funktion aufzurufen.

Hinweis: Dieses Feature ist ab PHP 5.3.0 verfügbar.

Beispiel #3 Nutzung von __invoke

<?php
class CallableClass {
  function 
__invoke($x) {
    
var_dump($x);
  }
}
$obj = new CallableClass;
$obj(5);
var_dump(is_callable($obj));
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

int(5)
bool(true)

__set_state

Diese statische Methode wird seit PHP 5.1.0 für Klassen aufgerufen, die mittels var_export() exportiert werden.

Der einzige Parameter dieser Methode ist ein Array, welches aus exportierten Eigenschaften der Form array('Eigenschaft' => Wert, ...) besteht.

Beispiel #4 Verwendung von __set_state (seit PHP 5.1.0)

<?php

class A
{
    public 
$var1;
    public 
$var2;

    public static function 
__set_state($an_array// seit PHP 5.1.0
    
{
        
$obj = new A;
        
$obj->var1 $an_array['var1'];
        
$obj->var2 $an_array['var2'];
        return 
$obj;
    }
}

$a = new A;
$a->var1 5;
$a->var2 'foo';

eval(
'$b = ' var_export($atrue) . ';'); // $b = A::__set_state(array(
                                            //    'var1' => 5,
                                            //    'var2' => 'foo',
                                            // ));
var_dump($b);

?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

object(A)#2 (2) {
  ["var1"]=>
  int(5)
  ["var2"]=>
  string(3) "foo"
}


Final-Schlüsselwort

PHP 5 führt das final-Schlüsselwort ein, welches Kindklassen davon abhält, Methoden zu überschreiben, indem man der Definition final voranstellt. Wenn die Klasse selbst als final definiert wird, kann sie nicht erweitert werden.

Beispiel #1 Beispiel für final-Methoden

<?php
class BaseClass {
   public function 
test() {
       echo 
"BaseClass::test() aufgerufen\n";
   }

   final public function 
moreTesting() {
       echo 
"BaseClass::moreTesting() aufgerufen\n";
   }
}

class 
ChildClass extends BaseClass {
   public function 
moreTesting() {
       echo 
"ChildClass::moreTesting() aufgerufen\n";
   }
}
// Erzeugt einen fatalen Fehler: Cannot override final method BaseClass::moreTesting()
?>

Beispiel #2 Beispiel für final-Klassen

<?php
final class BaseClass {
   public function 
test() {
       echo 
"BaseClass::test() aufgerufen\n";
   }

   
// Es macht hier keinen Unterschied, ob die Methode final ist oder nicht
   
final public function moreTesting() {
       echo 
"BaseClass::moreTesting() aufgerufen\n";
   }
}

class 
ChildClass extends BaseClass {
}
// Erzeugt einen fatalen Fehler: Class ChildClass may not inherit from final class (BaseClass)
?>

Hinweis: Eigenschaften können nicht als final deklariert werden; nur Klassen und Methoden können als final deklariert werden.



Objekte klonen

Eine Kopie eines Objektes mit vollständig replizierten Eigenschaften zu erzeugen ist nicht immer das gewünschte Verhalten. Ein gutes Beispiel für die Notwendigkeit von Kopierkonstruktoren ist ein Objekt, welches ein GTK Fenster repräsentiert und dieses Objekt enthält die Ressource des GTK-Fensters. Wenn Sie ein Duplikat dieses Objektes erzeugen, könnten Sie ein neues Fenster mit gleichen Eigenschaften erzeugen wollen und das neue Objekt soll die Ressource des neuen Fensters speichern. Ein weiteres Beispiel ist ein Objekt, welches eine Referenz auf ein anderes Objekt, das es benutzt, hält und wenn das Vaterobjekt repliziert wird, will man eine neue Instanz dieses anderen Objektes erzeugen, damit das Replikat eine eigene Kopie besitzt.

Eine Objektkopie wird durch die Nutzung des clone Schlüsselwortes (welches wenn möglich die __clone() Methode des Objektes aufruft) erzeugt. Die __clone() Methode eines Objektes kann nicht direkt aufgerufen werden.

$kopie_des_objektes = clone $objekt;

Wenn ein Objekt geklont wird, wird PHP 5 eine seichte Kopie der Eigenschaften des Objektes durchführen. Alle Eigenschaften, die Referenzen auf andere Variablen sind, werden Referenzen bleiben. Falls eine __clone() Methode definiert ist, wird die __clone() Methode des frisch erzeugten Objektes aufgerufen, um alle notwendigen Eigenschaften die geändert werden müssen ändern zu können.

Beispiel #1 Ein Objekt klonen

<?php
class SubObject
{
    static 
$instanzen 0;
    public 
$instanz;

    public function 
__construct() {
        
$this->instanz = ++self::$instanzen;
    }

    public function 
__clone() {
        
$this->instanz = ++self::$instanzen;
    }
}

class 
MyCloneable
{
    public 
$objekt1;
    public 
$objekt2;

    function 
__clone()
    {
        
// Erzwinge eine Kopie von this->object,
        // andernfalls wird es auf das selbe Objekt zeigen
        
$this->objekt1 = clone $this->objekt1;
    }
}

$obj = new MyCloneable();

$obj->objekt1 = new SubObject();
$obj->objekt2 = new SubObject();

$obj2 = clone $obj;


print(
"Original Objekt:\n");
print_r($obj);

print(
"geklontes Objekt:\n");
print_r($obj2);

?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

Original Object:
MyCloneable Object
(
    [object1] => SubObject Object
        (
            [instanz] => 1
        )

    [object2] => SubObject Object
        (
            [instanz] => 2
        )

)
Cloned Object:
MyCloneable Object
(
    [objekt1] => SubObject Object
        (
            [instanz] => 3
        )

    [objekt2] => SubObject Object
        (
            [instanz] => 2
        )

)


Objekte vergleichen

In PHP 5 ist der Vergleich von Objekten komplizierter als in PHP 4 und in stärkerer Übereinstimmung zu dem, was man von einer objektorientierten Programiersprache erwartet (nicht dass PHP 5 eine derartige Sprache wäre).

Wenn man den Vergleichsoperator (==) benutzt, werden Objektvariablen auf einfache Weise verglichen, nämlich: Zwei Objektinstanzen sind gleich, wenn Sie die gleichen Attribute haben und Instanzen der selben Klasse sind.

Wenn man andererseits den Identitätsoperator benutzt (===) sind zwei Objekte identisch, genau dann wenn sie die selbe Instanz der selben Klasse referenzieren.

Ein Beispiel wird diese Regeln verdeutlichen.

Beispiel #1 Beispiel für Objektvergleiche in PHP 5

<?php
function bool2str($bool)
{
    if (
$bool === false) {
        return 
'FALSE';
    } else {
        return 
'TRUE';
    }
}

function 
compareObjects(&$o1, &$o2)
{
    echo 
'o1 == o2 : ' bool2str($o1 == $o2) . "\n";
    echo 
'o1 != o2 : ' bool2str($o1 != $o2) . "\n";
    echo 
'o1 === o2 : ' bool2str($o1 === $o2) . "\n";
    echo 
'o1 !== o2 : ' bool2str($o1 !== $o2) . "\n";
}

class 
Flag
{
    public 
$flag;

    function 
Flag($flag true) {
        
$this->flag $flag;
    }
}

class 
OtherFlag
{
    public 
$flag;

    function 
OtherFlag($flag true) {
        
$this->flag $flag;
    }
}

$o = new Flag();
$p = new Flag();
$q $o;
$r = new OtherFlag();

echo 
"Zwei Instanzen der selben Klasse\n";
compareObjects($o$p);

echo 
"\nZwei Referenzen auf die selbe Instanz\n";
compareObjects($o$q);

echo 
"\nInstanzen zweier verschiedener Klassen\n";
compareObjects($o$r);
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

Zwei Instanzen der selben Klasse
o1 == o2 : TRUE
o1 != o2 : FALSE
o1 === o2 : FALSE
o1 !== o2 : TRUE

Zwei Referenzen auf die selbe Instanz
o1 == o2 : TRUE
o1 != o2 : FALSE
o1 === o2 : TRUE
o1 !== o2 : FALSE

Instanzen zweier verschiedener Klassen
o1 == o2 : FALSE
o1 != o2 : TRUE
o1 === o2 : FALSE
o1 !== o2 : TRUE

Hinweis: Extensions can define own rules for their objects comparison.



Type Hinting

PHP 5 führt Type Hinting ein. Funktionen sind damit fähig, Parameter zu zwingen, Objekte (indem man den Namen der Klasse im Funktionsprototyp spezifiziert) oder Arrays (seit PHP 5.1) zu sein. Wird dabei NULL als Vorgabewert für einen Parameter angegeben so ist dies ein weiterer gültiger Aufrufwert neben dem spezifizierten Typ.

Beispiel #1 Type Hinting Beispiele

<?php
// Eine Beispielklasse
class MyClass
{
    
/**
     * Eine Testfunktion
     *
     * Der erste Parameter muss ein Objekt des Typs OtherClass sein
     */
    
public function test(OtherClass $otherclass) {
        echo 
$otherclass->var;
    }


    
/**
     * Eine weitere Testfunktion
     *
     * Der erste Parameter muss ein Array sein
     */
    
public function test_array(array $input_array) {
        
print_r($input_array);
    }
}

// Eine weitere Beispielklasse
class OtherClass {
    public 
$var 'Hallo Welt';
}
?>

Wird der Type Hint nicht erfüllt, führt dies zu einem abfangbaren fatalen Fehler.

<?php
// Eine Instanz jeder Klasse
$myclass = new MyClass;
$otherclass = new OtherClass;

// Fatal Error: Argument 1 must be an object of class OtherClass
$myclass->test('hello');

// Fatal Error: Argument 1 must be an instance of OtherClass
$foo = new stdClass;
$myclass->test($foo);

// Fatal Error: Argument 1 must not be null
$myclass->test(null);

// Funktionier: Gibt Hallo Welt aus
$myclass->test($otherclass);

// Fatal Error: Argument 1 must be an array
$myclass->test_array('a string');

// Funktioniert: Gibt das Array aus
$myclass->test_array(array('a''b''c'));
?>

Type Hinting funktioniert ebenfalls mit Methoden

<?php
// Eine Beispielklasse
class MyClass {
    public 
$var 'Hallo Welt';
}

/**
 * Eine Testfunktion
 *
 * Der erste Parameter muss ein Objekt vom Typ MyClass sein
 */
function MyFunction (MyClass $foo) {
    echo 
$foo->var;
}

// Funktioniert
$myclass = new MyClass;
MyFunction($myclass);
?>

Type hinting mit möglichen NULL Werten:

<?php

/* Akzeptiert NULL Werte */
function test(stdClass $obj NULL) {

}

test(NULL);
test(new stdClass);

?>

Type Hints können nur vom Typen object und (seit PHP 5.1) array sein. Traditionelles Type Hinting mit int und string wird nicht unterstützt.



Späte statische Bindung

Beginnend mit PHP 5.3.0 unterstützt PHP späte statische Bindung ("Late static binding"). Hiermit kann die aufgerufene Klasse im Kontext statischer Vererbung referenziert werden.

Diese Funktionalität wurde in Hinblick auf die interne Perspektive als "späte statische Bindung" benannt. "Späte Bindung" bezieht sich auf die Tatsache, dass static:: nicht mehr über die Klasse, in der die aufgerufene Methode definiert ist, aufgelöst wird, stattdessen wird diese mit Hilfe von Laufzeitinformationen bestimmt. Die Benennung als "statische Bindung" beruht darauf, dass dieser Mechanismus unter anderem für statische Methodenaufrufe genutzt werden kann.

Beschränkungen von self::

Statische Referenzen auf die aktuelle Klasse wie self:: oder __CLASS__ werden mit Hilfe der Klasse, zu der die Methode gehört, also in welcher sie definiert ist, aufgelöst.

Beispiel #1 Nutzung von self::

<?php
class {
    public static function 
who() {
        echo 
__CLASS__;
    }
    public static function 
test() {
        
self::who();
    }
}

class 
extends {
    public static function 
who() {
         echo 
__CLASS__;
    }
}

B::test();
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

A

Nutzung später statischer Bindung

Späte statische Bindung versucht diese Beschränkung zu umgehen, indem ein neues Schlüsselwort eingeführt wird, dass die Klasse referenziert, die tatsächlich zur Laufzeit genutzt wurde, also im Wesentlichen ein Schlüsselwort, das es Ihnen gestattet im vorangegangenen Beispiel aus der aufgerufenen Methode test() die Klasse B zu referenzieren. Es wurde entschieden, kein neues Schlüsselwort einzuführen sondern statt dessen static zu verwenden, das bereits als reserviertes Schlüsselwort existierte.

Beispiel #2 Einfache Nutzung von static::

<?php
class {
    public static function 
who() {
        echo 
__CLASS__;
    }
    public static function 
test() {
        static::
who(); // statische Bindung
    
}
}

class 
extends {
    public static function 
who() {
         echo 
__CLASS__;
    }
}

B::test();
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

B

Hinweis: In statischen Methoden verhält sich static:: nicht wie $this! $this folgt den Vererbungsregeln, während static:: dies nicht tut. Dieser Unterschied wird später in diesem Abschnitt noch genauer beschrieben.

Beispiel #3 Nutzung von static:: außerhalb eines statischen Kontexts

<?php
class TestChild extends TestParent {
    public function 
__construct() {
        static::
who();
    }

    public function 
test() {
        
$o = new TestParent();
    }

    public static function 
who() {
        echo 
__CLASS__."\n";
    }
}

class 
TestParent {
    public function 
__construct() {
        static::
who();
    }

    public static function 
who() {
        echo 
__CLASS__."\n";
    }
}
$o = new TestChild;
$o->test();

?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

TestChild
TestParent

Hinweis: Die Auflösung später statischer Bindungen endet mit einem vollständig aufgelösten statischen Aufruf ohne Alternative. Statische Aufrufe, die Schlüsselworte wie parent:: oder self:: nutzen, geben dagegen die Aufrufinformationen weiter.

Beispiel #4 Weitergegebene und nicht weitergegebene Aufrufe

<?php
class {
    public static function 
foo() {
        static::
who();
    }

    public static function 
who() {
        echo 
__CLASS__."\n";
    }
}

class 
extends {
    public static function 
test() {
        
A::foo();
        
parent::foo();
        
self::foo();
    }

    public static function 
who() {
        echo 
__CLASS__."\n";
    }
}
class 
extends {
    public static function 
who() {
        echo 
__CLASS__."\n";
    }
}

C::test();
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

A
C
C

Sonderfälle

Es gibt in PHP viele verschiedene Wege den Aufruf einer Methode auszulösen. Da bei später statischer Bindung die Auflösung von Aufrufen auf Laufzeitinformationen beruht, kann sie in speziellen Fällen zu unerwarteten Ergebnissen führen.

Beispiel #5 Späte statische Bindung in 'magischen' Methoden

<?php
class {

   protected static function 
who() {
        echo 
__CLASS__."\n";
   }

   public function 
__get($var) {
       return static::
who();
   }
}

class 
extends {

   protected static function 
who() {
        echo 
__CLASS__."\n";
   }
}

$b = new B;
$b->foo;
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

B


Objects and references

One of the key-point of PHP5 OOP that is often mentioned is that "objects are passed by references by default" This is not completely true. This section rectifies that general thought using some examples. </