Php new namespace class

Php new namespace class

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

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

This is functionally equivalent to:

Example #2 Accessing global classes outside a namespace

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

Example #3 Accessing internal classes in namespaces

namespace foo ;
$a = new \ stdClass ;

function test (\ ArrayObject $parameter_type_example = 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

// using a class from the current namespace as a parameter type
function test ( MyClass $parameter_type_example = null ) <>
// another way to use a class from the current namespace as a parameter type
function test (\ foo \ MyClass $parameter_type_example = 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 \my\name or \name resolve?

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

Example #5 Fully Qualified names

namespace foo ;
$a = new \ my \ name (); // instantiates «my\name» 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 my\name resolve?

Names that contain a backslash but do not begin with a backslash like my\name 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 my\name .

Otherwise, the current namespace name is prepended to my\name .

Example #6 Qualified names

namespace foo ;
use blah \ blah as foo ;

$a = new my \ name (); // instantiates «foo\my\name» class
foo \ bar :: name (); // calls static method «name» in class «blah\blah\bar»
my \ bar (); // calls function «foo\my\bar»
$a = my \ BAR ; // sets $a to the value of constant «foo\my\BAR»
?>

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.

Читайте также:  Html checkbox yii2 checked

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

namespace foo ;
use blah \ blah as foo ;

$a = new name (); // instantiates «foo\name» class
foo :: name (); // calls static method «name» in class «blah\blah»
?>

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

namespace foo ;
use blah \ blah as foo ;

function my () <>
function foo () <>
function sort (& $a )
\ sort ( $a ); // calls the global function «sort»
$a = array_flip ( $a );
return $a ;
>

my (); // calls «foo\my»
$a = strlen ( ‘hi’ ); // calls global function «strlen» because «foo\strlen» does not exist
$arr = array( 1 , 3 , 2 );
$b = sort ( $arr ); // calls function «foo\sort»
$c = foo (); // calls function «foo\foo» — import is not applied

$a = FOO ; // sets $a to value of constant «foo\FOO» — import is not applied
$b = INI_ALL ; // sets $b to value of global constant «INI_ALL»
?>

Import names must not conflict with classes defined in the same file.

The following script combinations are legal:

namespace my \ stuff ;
include ‘file1.php’ ;
include ‘another.php’ ;

use another \ thing as MyClass ;
$a = new MyClass ; // instantiates class «thing» from namespace another
?>

There is no name conflict, even though the class MyClass exists within the my\stuff 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.

namespace my \ stuff ;
use another \ thing 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

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

$a = «dangerous\name» ; // \n is a newline inside double quoted strings!
$obj = new $a ;

$a = ‘not\at\all\dangerous’ ; // 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

namespace bar ;
$a = FOO ; // produces notice — undefined constants «FOO» assumed «FOO»;
$a = \ FOO ; // fatal error, undefined namespace constant FOO
$a = Bar \ FOO ; // fatal error, undefined namespace constant bar\Bar\FOO
$a = \ Bar \ FOO ; // fatal error, undefined namespace constant Bar\FOO
?>

Читайте также:  Ubuntu apache nginx php fpm

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

namespace bar ;
const NULL = 0 ; // fatal error;
const true = ‘stupid’ ; // also fatal error;
// etc.
?>

User Contributed Notes 6 notes

There is a way to define a namespaced constant that is a special, built-in constant, using define function and setting the third parameter case_insensitive to false:

namespace foo ;
define ( __NAMESPACE__ . ‘\NULL’ , 10 ); // defines the constant NULL in the current namespace
var_dump ( NULL ); // will show 10
var_dump ( null ); // will show NULL
?>

No need to specify the namespace in your call to define(), like it happens usually
namespace foo ;
define ( INI_ALL , ‘bar’ ); // produces notice — Constant INI_ALL already defined. But:

define ( __NAMESPACE__ . ‘\INI_ALL’ , ‘bar’ ); // defines the constant INI_ALL in the current namespace
var_dump ( INI_ALL ); // will show string(3)»bar». Nothing unespected so far. But:

define ( ‘NULL’ , 10 ); // defines the constant NULL in the current namespace.
var_dump ( NULL ); // will show 10
var_dump ( null ); // will show NULL
?>

If the parameter case_insensitive is set to true
namespace foo ;
define ( __NAMESPACE__ . ‘\NULL’ , 10 , true ); // produces notice — Constant null already defined
?>

When creating classes or calling static methods from within namespaces using variables, you need to keep in mind that they require the full namespace in order for the appropriate class to be used; you CANNOT use an alias or short name, even if it is called within the same namespace. Neglecting to take this into account can cause your code to use the wrong class, throw a fatal missing class exception, or throw errors or warnings.

In these cases, you can use the magic constant __NAMESPACE__, or specify the full namespace and class name directly. The function class_exists also requires the full namespace and class name, and can be used to ensure that a fatal error won’t be thrown due to missing classes.

namespace Foo ;
class Bar public static function test () return get_called_class ();
>
>

namespace Foo \ Foo ;
class Bar extends \ Foo \ Bar >

var_dump ( Bar :: test () ); // string(11) «Foo\Foo\Bar»

$bar = ‘Foo\Bar’ ;
var_dump ( $bar :: test () ); // string(7) «Foo\Bar»

$bar = __NAMESPACE__ . ‘\Bar’ ;
var_dump ( $bar :: test () ); // string(11) «Foo\Foo\Bar»

$bar = ‘Bar’ ;
var_dump ( $bar :: test () ); // FATAL ERROR: Class ‘Bar’ not found or Incorrect class \Bar used

[Editor’s note: that behavior is caused by a bug in PHP 7.0, which has been fixed as of PHP 7.0.7.]

Regarding the entry «Import names cannot conflict with classes defined in the same file».
— I found that since PHP 7.0 this is no longer the case.
In PHP 7.0 you can have a class with a name that matches an imported class (or namespace or both at the same time).

namespace ns1 <
class ns1 <
public static function write () <
echo «ns1\\ns1::write()\n» ;
>
>
>

namespace ns1 \ ns1 <
class ns1c <
public static function write () <
echo «ns1\\ns1\\ns1c::write()\n» ;
>
>
>

namespace ns2 <
use ns1 \ ns1 as ns1 ; // both a class in ns1, and a namespace ns1\ns1

Читайте также:  METANIT.COM

// the next class causes fatal error in php 5.6, not in 7.0
class ns1 <
public static function write () <
echo «ns2\\ns1::write()\n» ;
>
>

ns1 :: write (); // calls imported ns1\ns1::write()
ns1 \ ns1c :: write (); // calls imported ns1\ns1\ns1c::write()
namespace\ ns1 :: write (); // calls ns2\ns1::write()
>
?>

Regarding «Neither functions nor constants can be imported via the use statement.» Actually you can do it in PHP 5.6+:

// importing a function (PHP 5.6+)
use function My \ Full \ functionName ;

// aliasing a function (PHP 5.6+)
use function My \ Full \ functionName as func ;

// importing a constant (PHP 5.6+)
use const My \ Full \ CONSTANT ;
?>

Just like class names currently namespaces are not case sensitive. So no errors will be shown here:

namespace Foo ;
class Bar public function __construct () echo ‘Map constructed’ ;
>
>

To correct manolachef’s answer: define() ALWAYS defines constants in the GLOBAL namespace.

As nl-x at bita dot nl states in the note at http://www.php.net/manual/en/function.define.php, the constant «NULL» can be defined with define() case-sensitively, but can only be retrieved with constant(), leaving the meaning of NULL uppercase keyword as the only value of the type null.

  • Namespaces
    • Namespaces overview
    • Defining namespaces
    • Declaring sub-​namespaces
    • Defining multiple namespaces in the same file
    • Using namespaces: Basics
    • Namespaces and dynamic language features
    • namespace keyword and _​_​NAMESPACE_​_​ constant
    • Using namespaces: Aliasing/Importing
    • Global space
    • Using namespaces: fallback to global function/constant
    • Name resolution rules
    • FAQ: things you need to know about namespaces

    Источник

    Пространства имён

    The keyword ‘use’ has two different applications, but the reserved word table links to here.

    It can apply to namespace constucts:

    file1:
    class Cat <
    static function says () > ?>

    file2:
    class Dog static function says () > ?>

    file3:
    class Animal static function breathes () > ?>

    file4:
    include ‘file1.php’ ;
    include ‘file2.php’ ;
    include ‘file3.php’ ;
    use foo as feline ;
    use bar as canine ;
    use animate ;
    echo \ feline \ Cat :: says (), «
    \n» ;
    echo \ canine \ Dog :: says (), «
    \n» ;
    echo \ animate \ Animal :: breathes (), «
    \n» ; ?>

    Note that
    felineCat::says()
    should be
    \feline\Cat::says()
    (and similar for the others)
    but this comment form deletes the backslash (why. )

    The ‘use’ keyword also applies to closure constructs:

    $callback =
    function ( $pricePerItem ) use ( $tax , & $total )

    $total += $pricePerItem * ( $tax + 1.0 );
    >;

    array_walk ( $products_costs , $callback );
    return round ( $total , 2 );
    >
    ?>

    Tested on PHP 7.0.5, Windows
    The line «use animate;» equals the line «use animate as animate;»
    but the «use other\animate;» equals «use other\animate as animate;»

    file1:
    class Cat <
    static function says () > ?>

    file2:
    class Dog static function says () > ?>

    file3:
    class Animal static function breathes () > ?>

    file4:
    include ‘file1.php’ ;
    include ‘file2.php’ ;
    include ‘file3.php’ ;
    use foo as feline ;
    use bar as canine ;
    use other \ animate ; //use other\animate as animate;
    echo feline \ Cat :: says (), «
    \n» ;
    echo canine \ Dog :: says (), «
    \n» ;
    echo \ animate \ Animal :: breathes (), «
    \n» ; ?>

    In addition to using namespaces and closures, the use keyword has another new meaning as of PHP 5.4 — using traits:

    trait Hello public function sayHello () echo ‘Hello ‘ ;
    >
    >

    trait World public function sayWorld () echo ‘World’ ;
    >
    >

    class MyHelloWorld use Hello , World ;
    public function sayExclamationMark () echo ‘!’ ;
    >
    >

    Источник

Оцените статью