downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | conferences | my php.net

search for in the

Usando namespaces> <Namespaces - Visão geral
[edit] Last updated: Fri, 26 Apr 2013

view this page in

Definição de Namespace

O namespace é declarado usando a palavra chave namespace, que deve ser usada logo no começo do arquivo. Exemplo:

Exemplo #1 Defining namespace

<?php
    
namespace MyProject\DB;
    
    const 
CONNECT_OK 1;

    class 
Connection /* ... */ }
    
    function 
connect() { /* ... */  }
    
?>
Um mesmo nome de namespace pode ser usado em múltiplos arquivos.

Namespace pode conter definições de classes, constantes e funções, mas não código livre.

Definição do Namespace fazem seguinte:

  • Dentro do namespace, todas os nomes de as classes, funções e constantes na definição são automaticamente prefixados com o nome do namespace. O nome da classe é sempre o nome completo, i.e. no exemplo acima a classe é chamada MyProject\DB\Connection.
  • Definição de constantes criam constantes que são compostas do nome do namespace e o nome da constante. Com constantes de classes, constantes do namespace podem somente conter valores estáticos.
  • Nome não qualificado de classe (i.e., nome não contém \) são resolvido em runtime seguindo este procedimento:

    1. A classe é verificada dentro do atual namespace (i.e. prefixando o nome com o atual nome do namespace) sem tentar fazer autoload.
    2. A classe é verificada dentro do namespace global sem tentar fazer autoload.
    3. É tentado autoloading para nomes no namespace atual.
    4. Se anteriormente falhou, a verificação falha.

  • Nome não qualificado de função (i.e., nome não contém \) é verificado em tempo de execução primeiro no namespace atual e então no espaço global.

  • Nome de constantes não qualificada são verificadas primeiro no namespace atual e então entre as constantes globalmente definidas.

Veja também em regras de resolução de nomes.



Usando namespaces> <Namespaces - Visão geral
[edit] Last updated: Fri, 26 Apr 2013
 
add a note add a note User Contributed Notes Definição de Namespace - [8 notes]
up
11
danbettles at yahoo dot co dot uk
4 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
3
David Drakard
4 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
1
Anonymous
5 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
4
jeremeamia at gmail dot com
3 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
0
huskyr at gmail dot com
3 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
0
Baptiste
4 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
-1
parsmizban.com
10 months ago
You can use this as a namespace declaration:

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

echo
"parsmizban";
?>
up
-1
Chris
2 days ago
Namespaces don't seem to mix well with UTF-8 encoding. I received plenty of complaints that my namespace was not the first statement in the document (Although it obviously was).

Changing my PHP file to ANSI encoding fixed the problem.

 
show source | credits | stats | sitemap | contact | advertising | mirror sites