Defining namespaces

(PHP 5 >= 5.3.0, PHP 7)

Although any valid PHP code can be contained within a namespace, only the following
types of code are affected by namespaces: classes (including abstracts and traits), interfaces, functions and constants.

Namespaces are declared using the namespace
keyword. A file containing a namespace must declare the namespace
at the top of the file before any other code - with one exception: the
declare keyword.

The only code construct allowed before a namespace declaration is the
declare statement, for defining encoding of a source file. In addition,
no non-PHP code may precede a namespace declaration, including extra whitespace:

Example #2 Declaring a single namespace

<html><?phpnamespace MyProject; // fatal error - namespace must be the first statement in the script?>

In addition, unlike any other PHP construct, the same namespace may be defined
in multiple files, allowing splitting up of a namespace's contents across the filesystem.

User Contributed Notes 10 notes

...and you still get "Namespace declaration statement has to be the very first statement in the script" Fatal error, then you probably use UTF-8 encoding (which is good) with Byte Order Mark, aka BOM (which is bad). Try to convert your files to "UTF-8 without BOM", and it should be ok.

define() will define constants exactly as specified. So, if you want to define a constant in a namespace, you will need to specify the namespace in your call to define(), even if you're calling define() from within a namespace. The following examples will make it clear.

The following code will define the constant "MESSAGE" in the global namespace (i.e. "\MESSAGE").

I agree with SR, the new namespaces feature has solved a number of problems for me which would have required horrible coding to solve otherwise.

An example use:Say you are making a small script, and write a class to connect to a database, calling it 'connection'. If you find your script useful and gradually expand it into a large application, you may want to rename the class. Without namespaces, you have to change the name and every reference to it (say in inheriting objects), possibly creating a load of bugs. With namespaces you can drop the related classes into a namespace with one line of code, and less chance of errors.

This is by no means one of the biggest problems namespaces solve; I would suggest reading about their advantages before citicising them. They provide an elegant solutions to several problems involved in creating complex systems.

(...)Namespaces are declared using the namespace keyword. A file containing a namespace must declare the namespace at the top of the file before any other code - with one exception: the declare keyword.

end quote.

So we have a title that talks 'defining' and a piece of text that talks 'declare' three times, one of which could be referring to some other 'declare' than the former two.