ADS - GoldenWeb.it Directory "Premium" Links

Grafica 3B
Grafica 3B si occupa di comunicazione a 360° per le aziende di Milano e non solo. Un team di esperti di marketing in grado di studiare i bisogni, progettare e sviluppare un piano pubblicitario strategico e mirato ad aumentare la visibilità. Ci occupiamo nello specifico dello studio grafico di loghi, cataloghi, menu, banner e più in generale della definizione di una brand identity con servizio di stampa digitale piccoli e grandi formati. L'agenzia opera anche nel settore web
Risanamento Edifici - Risparmio Energetico
Casaswiss è una società specializzata nel risanamento degli edifici.
Inquinamento Italia
Il portale dell’inquinamento in Italia: un sito divulgativo per imparare a capirlo, misurarlo e prevenirlo.
Scaricatore di condensa automatico aria compressa
Trappole e scaricatori di condensa che in modo automatico lavorano sui compressori o sui sistemi che genera aria compressa.

Inserisci il tuo sito nella directory...

Manuale PHP


FAQ: things you need to know about namespaces

(PHP 5 >= 5.3.0)

This FAQ is split into two sections: common questions, and some specifics of implementation that are helpful to understand fully.

First, the common questions.

  1. If I don't use namespaces, should I care about any of this?
  2. How do I use internal or global classes in a namespace?
  3. How do I use namespaces classes functions, or constants in their own namespace?
  4. How does a name like myname or name resolve?
  5. How does a name like myname resolve?
  6. How does an unqualified class name like name resolve?
  7. How does an unqualified function name or unqualified constant name like name resolve?

There are a few implementation details of the namespace implementations that are helpful to understand.

  1. Import names cannot conflict with classes defined in the same file.
  2. Nested namespaces are not allowed.
  3. Neither functions nor constants can be imported via the use statement.
  4. Dynamic namespace names (quoted identifiers) should escape backslash.
  5. Undefined Constants referenced using any backslash die with fatal error
  6. Cannot override special constants NULL, TRUE, FALSE, ZEND_THREAD_SAFE or ZEND_DEBUG_BUILD

If I don't use namespaces, should I care about any of this?

No. Namespaces do not affect any existing code in any way, or any as-yet-to-be-written code that does not contain namespaces. You can write this code if you wish:

Example #1 Accessing global classes outside a namespace

<?php
$a 
= new stdClass;
?>

This is functionally equivalent to:

Example #2 Accessing global classes outside a namespace

<?php
$a 
= new stdClass;
?>

How do I use internal or global classes in a namespace?

Example #3 Accessing internal classes in namespaces

<?php
namespace foo;
$a = new stdClass;

function 
test(ArrayObject $typehintexample null) {}

$a DirectoryIterator::CURRENT_AS_FILEINFO;

// extending an internal or global class
class MyException extends Exception {}
?>

How do I use namespaces classes, functions, or constants in their own namespace?

Example #4 Accessing internal classes, functions or constants in namespaces

<?php
namespace foo;

class 
MyClass {}

// using a class from the current namespace as a type hint
function test(MyClass $typehintexample null) {}
// another way to use a class from the current namespace as a type hint
function test(fooMyClass $typehintexample null) {}

// extending a class from the current namespace
class Extended extends MyClass {}

// accessing a global function
$a globalfunc();

// accessing a global constant
$b INI_ALL;
?>

How does a name like myname or name resolve?

Names that begin with a always resolve to what they look like, so myname is in fact myname, and Exception is Exception.

Example #5 Fully Qualified names

<?php
namespace foo;
$a = new myname(); // instantiates "myname" class
echo strlen('hi'); // calls function "strlen"
$a INI_ALL// $a is set to the value of constant "INI_ALL"
?>

How does a name like myname resolve?

Names that contain a backslash but do not begin with a backslash like myname can be resolved in 2 different ways.

If there is an import statement that aliases another name to my, then the import alias is applied to the my in myname.

Otherwise, the current namespace name is prepended to myname.

Example #6 Qualified names

<?php
namespace foo;
use 
blahblah as foo;

$a = new myname(); // instantiates "foomyname" class
foobar::name(); // calls static method "name" in class "blahblahbar"
mybar(); // calls function "foomybar"
$a myBAR// sets $a to the value of constant "foomyBAR"
?>

How does an unqualified class name like name resolve?

Class names that do not contain a backslash like name can be resolved in 2 different ways.

If there is an import statement that aliases another name to name, then the import alias is applied.

Otherwise, the current namespace name is prepended to name.

Example #7 Unqualified class names

<?php
namespace foo;
use 
blahblah as foo;

$a = new name(); // instantiates "fooname" class
foo::name(); // calls static method "name" in class "blahblah"
?>

How does an unqualified function name or unqualified constant name like name resolve?

Function or constant names that do not contain a backslash like name can be resolved in 2 different ways.

First, the current namespace name is prepended to name.

Finally, if the constant or function name does not exist in the current namespace, a global constant or function name is used if it exists.

Example #8 Unqualified function or constant names

<?php
namespace foo;
use 
blahblah as foo;

const 
FOO 1;

function 
my() {}
function 
foo() {}
function 
sort(&$a)
{
    
sort($a);
    
$a array_flip($a);
    return 
$a;
}

my(); // calls "foomy"
$a strlen('hi'); // calls global function "strlen" because "foostrlen" does not exist
$arr = array(1,3,2);
$b sort($arr); // calls function "foosort"
$c foo(); // calls function "foofoo" - import is not applied

$a FOO// sets $a to value of constant "fooFOO" - import is not applied
$b INI_ALL// sets $b to value of global constant "INI_ALL"
?>

Import names cannot conflict with classes defined in the same file.

The following script combinations are legal:

file1.php

<?php
namespace mystuff;
class 
MyClass {}
?>

another.php

<?php
namespace another;
class 
thing {}
?>

file2.php

<?php
namespace mystuff;
include 
'file1.php';
include 
'another.php';

use 
anotherthing as MyClass;
$a = new MyClass// instantiates class "thing" from namespace another
?>

There is no name conflict, even though the class MyClass exists within the mystuff namespace, because the MyClass definition is in a separate file. However, the next example causes a fatal error on name conflict because MyClass is defined in the same file as the use statement.

<?php
namespace mystuff;
use 
anotherthing as MyClass;
class 
MyClass {} // fatal error: MyClass conflicts with import statement
$a = new MyClass;
?>

Nested namespaces are not allowed.

PHP does not allow nesting namespaces

<?php
namespace mystuff {
    namespace 
nested {
        class 
foo {}
    }
}
?>
However, it is easy to simulate nested namespaces like so:
<?php
namespace mystuffnested {
    class 
foo {}
}
?>

Neither functions nor constants can be imported via the use statement.

The only elements that are affected by use statements are namespaces and class names. In order to shorten a long constant or function, import its containing namespace

<?php
namespace mine;
use 
ultralongnsname;

$a nameCONSTANT;
namefunc();
?>

Dynamic namespace names (quoted identifiers) should escape backslash

It is very important to realize that because the backslash is used as an escape character within strings, it should always be doubled when used inside a string. Otherwise there is a risk of unintended consequences:

Example #9 Dangers of using namespaced names inside a double-quoted string

<?php
$a 
= new "dangerousname"// n is a newline inside double quoted strings!
$obj = new $a;

$a = new 'notatalldangerous'// no problems here.
$obj = new $a;
?>
Inside a single-quoted string, the backslash escape sequence is much safer to use, but it is still recommended practice to escape backslashes in all strings as a best practice.

Undefined Constants referenced using any backslash die with fatal error

Any undefined constant that is unqualified like FOO will produce a notice explaining that PHP assumed FOO was the value of the constant. Any constant, qualified or fully qualified, that contains a backslash will produce a fatal error if not found.

Example #10 Undefined constants

<?php
namespace bar;
$a FOO// produces notice - undefined constants "FOO" assumed "FOO";
$a FOO// fatal error, undefined namespace constant FOO
$a BarFOO// fatal error, undefined namespace constant barBarFOO
$a BarFOO// fatal error, undefined namespace constant BarFOO
?>

Cannot override special constants NULL, TRUE, FALSE, ZEND_THREAD_SAFE or ZEND_DEBUG_BUILD

Any attempt to define a namespaced constant that is a special, built-in constant results in a fatal error

Example #11 Undefined constants

<?php
namespace bar;
const 
NULL 0// fatal error;
const true 'stupid'// also fatal error;
// etc.
?>