Mehrere Namespaces in derselben Datei definieren

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

Es können auch mehrere Namespaces in derselben Datei definiert werden. Es gibt hierfür zwei mögliche Schreibweisen:

Beispiel #1 Mehrere Namespaces definieren, einfache Kombinationssyntax

<?php
namespace MyProject;

const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */  }

namespace AnotherProject;

const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */  }
?>

Diese Syntax ist nicht die empfohlene Syntax, um mehrere Namespaces in einer einzigen Datei zusammenzuführen. Stattdessen wird die geklammerte Syntax empfohlen.

Beispiel #2 Mehrere Namespaces definieren, geklammerte Syntax

<?php
namespace MyProject {

const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */  }
}

namespace AnotherProject {

const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */  }
}
?>

Es wird stark von der Programmierpraxis, mehrere Namespaces in einer Datei zu definieren, abgeraten. Der wichtigste Einsatzzweck dieser Möglichkeit ist es, mehrere PHP-Skripte in derselben Datei zusammenzuführen.

Um Code ohne Namensräume mit solchem mit Namensräumen zusammenzuführen, wird nur die geklammerte Syntax unterstützt. Globaler Code sollte in einem Namespace-Statement ohne Namespace eingeschlossen werden:

Beispiel #3 Mehrere Namespaces und Code ohne Namespace deklarieren

<?php
namespace MyProject {

const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */  }
}

namespace { // global code
session_start();
$a = MyProject\connect();
echo MyProject\Connection::start();
}
?>

Es darf kein PHP-Code außerhalb der Namespace-Klammern existieren, abgesehen von einem beginnenden declare-Ausdruck.

Beispiel #4 Mehrere Namespaces und Code ohne Namespace deklarieren

<?php
declare(encoding='UTF-8');
namespace MyProject {

const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */  }
}

namespace { // globaler Code
session_start();
$a = MyProject\connect();
echo MyProject\Connection::start();
}
?>