PHP 5.4.33 Released

Defining namespaces

(PHP 5 >= 5.3.0)

Although any valid PHP code can be contained within a namespace, only four types of code are affected by namespaces: classes, 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.

Przykład #1 Declaring a single namespace

<?php
namespace MyProject;

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

?>
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:

Przykład #2 Declaring a single namespace

<html>
<?php
namespace 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.

add a note add a note

User Contributed Notes 11 notes

up
44
danbettles at yahoo dot co dot uk
5 years ago
Regarding constants defined with define() inside namespaces...

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").

<?php
namespace test;
define('MESSAGE', 'Hello world!');
?>

The following code will define two constants in the "test" namespace.

<?php
namespace test;
define('test\HELLO', 'Hello world!');
define(__NAMESPACE__ . '\GOODBYE', 'Goodbye cruel world!');
?>
up
22
jeremeamia at gmail dot com
5 years ago
You should not try to create namespaces that use PHP keywords. These will cause parse errors.

Examples:

<?php
namespace Project/Classes/Function; // Causes parse errors
namespace Project/Abstract/Factory; // Causes parse errors
?>
up
17
FatBat
1 year ago
Expanding on @danbettles note, it is better to always be explicit about which constant to use.

<?php
   
namespace NS;

   
define(__NAMESPACE__ .'\foo','111');
   
define('foo','222');

    echo
foo// 111.
   
echo \foo// 222.
   
echo \NS\foo  // 111.
   
echo NS\foo  // fatal error. assumes \NS\NS\foo.
?>
up
18
huskyr at gmail dot com
4 years ago
"A file containing a namespace must declare the namespace at the top of the file before any other code"

It might be obvious, but this means that you *can* include comments and white spaces before the namespace keyword.

<?php
// Lots
// of
// interesting
// comments and white space

namespace Foo;
class
Bar {
}
?>
up
5
Baptiste
6 years ago
There is nothing wrong with PHP namespaces, except that those 2 instructions give a false impression of package management.
... while they just correspond to the "with()" instruction of Javascript.

By contrast, a package is a namespace for its members, but it offers more (like deployment facilities), and a compiler knows exactly what classes are in a package, and where to find them.
up
2
Anonymous
6 years ago
@ RS: Also, you can specify how your __autoload() function looks for the files. That way another users namespace classes cannot overwrite yours unless they replace your file specifically.
up
2
David Drakard
6 years ago
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.
up
0
Najeem M Illyas
4 days ago
While executing the script I am getting error:

<?php
namespace SebastianBergmann\Money;
/**
* Money
*
/

class MoneyTest extends \PHPUnit_Framework_TestCase
{
    /**
  
}

?>

C:\>phpunit --coverage-html ./report C:\xampp\htdocs\unit

Fatal error: Namespace declaration statement has to be the very first statement
in the script in C:\xampp\htdocs\unit\MoneyTest.php on line 2

Call Stack:
    0.0000     124064   1. {main}() C:\xampp\php\phpunit:0
    0.0000     359648   2. PHPUnit_TextUI_Command::main() C:\xampp\php\phpunit:4
6
    0.0000     363064   3. PHPUnit_TextUI_Command->run() C:\xampp\php\pear\PHPUn
it\TextUI\Command.php:129
    0.0100     542472   4. PHPUnit_Runner_BaseTestRunner->getTest() C:\xampp\php
\pear\PHPUnit\TextUI\Command.php:150
    0.0100     681336   5. PHPUnit_Framework_TestSuite->addTestFiles() C:\xampp\
php\pear\PHPUnit\Runner\BaseTestRunner.php:96
    0.0100     681768   6. PHPUnit_Framework_TestSuite->addTestFile() C:\xampp\p
hp\pear\PHPUnit\Framework\TestSuite.php:416
    0.0200     739488   7. PHPUnit_Util_Fileloader::checkAndLoad() C:\xampp\php\
pear\PHPUnit\Framework\TestSuite.php:355
    0.0200     739600   8. PHPUnit_Util_Fileloader::load() C:\xampp\php\pear\PHP
Unit\Util\Fileloader.php:76

Here in the error:
Fatal error: Namespace declaration statement has to be the very first statement
in the script in C:\xampp\htdocs\unit\MoneyTest.php on line 2

There is no error found in the code, but phpunit is throwing the error.
up
0
kuzawinski dot marcin at NOSPAM dot gmail dot com
1 month ago
If your code looks like this:

<?php
   
namespace NS;
?>

...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.
up
-2
Roadowl
6 months ago
quote:
Defining namespaces

(...)
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.

Please, documentation authors -- get your act together, finally.
up
-24
wyattbiker
1 year ago
<?php
//Even though you cant add anything before the 1st namespace, you can add something before subsequent namespaces.
namespace MyProject;

function
myfunc(){
    return
1;
}
echo
myfunc();
?>
<p>Here I can add stuff before the 2nd namespace</p>
<?php

namespace MyProject2;

function
myfunc(){
    return
2;
}
echo
myfunc();
?>
<p>Switch back to first namespace</p>
<?php
namespace MyProject;
echo
myfunc();
?>
To Top