FAQ: things you need to know about namespaces

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

First, the common questions. 

1. If I don't use namespaces, shouldI care about any of this?  

2. How do I use internal or globalclasses in a namespace?  

3. How do I use namespaces classesfunctions, or constants in their own namespace?  

4. How does a name like \my\name or \nameresolve?   

5. How does a name like my\name resolve?  

6. How does an unqualified class namelike name resolve?  

7. How does an unqualified functionname or unqualified constant namelike name resolve?  

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

1. Import names cannot conflict withclasses defined in the same file.  

2. Nested namespaces are not allowed.   

3. Neither functions norconstants can be imported via the usestatement.  

4. Dynamic namespace names (quotedidentifiers) should escape backslash.  

5. Undefined Constants referencedusing any backslash die with fatal error  

6. Cannot override specialconstants 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 anyas-yet-to-be-written code that does not contain namespaces. You canwrite 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 ownnamespace? 

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(\foo\MyClass $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 \my\name or \nameresolve? 

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

Example #5 Fully Qualified names

<?php

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 isan import statement that aliases another name to my, thenthe import alias is applied to the my in my\name. 

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

Example #6 Qualified names

<?php

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. 

If there isan import statement that aliases another name to name, thenthe import alias is applied. 

Otherwise, the current namespace name is prepended to name. 

Example #7 Unqualified class names

<?php

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 namelike 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 existin the current namespace, a global constant or function nameis used if it exists. 

Example #8 Unqualified function or constant names

<?php

namespace foo;

use blah\blah as foo;

const FOO = 1;

function my() {}

function foo() {}

function sort(&$a)

{

    sort($a);

    $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 cannot conflict with classes defined in the same file.

The following script combinations are legal: 

file1.php

<?php

namespace my\stuff;

class MyClass {}

?>  

another.php

<?php

namespace another;

class thing {}

?>  

file2.php

<?php

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 existswithin the my\stuff namespace, because the MyClass definition isin a separate file. However, the next example causes a fatal error on name conflictbecause MyClass is defined in the same file as the use statement. 

<?php

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 

<?php

namespace my\stuff {

    namespace nested {

        class foo {}

    }

}

?>  

However, it is easy to simulate nested namespaces like so: 

<?php

namespace my\stuff\nested {

    class foo {}

}

?>  

Neither functions nor constants can be imported via the usestatement.

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

<?php

namespace mine;

use ultra\long\ns\name;

$a = name\CONSTANT;

name\func();

?>  

Dynamic namespace names (quoted identifiers) should escape backslash

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

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

<?php

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

$obj = new $a;

$a = new '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 itis 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 willproduce a notice explaining that PHP assumed FOO was the valueof the constant. Any constant, qualified or fully qualified, that contains abackslash 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 = Bar\FOO; // fatal error, undefined namespace constant bar\Bar\FOO

$a = \Bar\FOO; // fatal error, undefined namespace constant Bar\FOO

?>  

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 constantresults in a fatal error 

Example #11 Undefined constants

<?php

namespace bar;

const NULL = 0; // fatal error;

const true = 'stupid'; // also fatal error;

// etc.

?> 

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论

热门产品

php编程基础教程.pptx|php编程培训,php,编程,基础,教程,pptx
php编程基础教程.pptx

历史上的今天:04月20日

ThinkPHP5快速入门基础

ThinkPHP5快速入门基础一、基础快速入门 ( 一 ) :基础本章介绍了 ThinkPHP5 .0 的安装及基本使用 ,并给出了一个最简单的示例带你了解如何开始开发 ,主要包 含 :简介官网下载 omposer安装和更新CGit下载和更新目录结构运行环境入口文件调试模式控制器视图读取数据总结在学习 ThinkPHP5.0 之前 ,如果你还不理解面向对象和命名空间的概念 ,建议首先去PHP手册恶

ThinkPHP5快速入门

ThinkPHP5快速入门目 录零、序言一、基础二、URL和路由三、请求和响应四、数据库五、查询语言六、模型和关联 (1)模型定义 (2)基础操作 (3)读取器和修改器 (4)类型转换和自动完成 (5)查询范围 (6)输入和验证 (7)关联 (8)模型输出七、视图和模板八、调试和日志九、API开发十、命令行工具十一、扩展十二、杂项SessionCookie验证

热门专题

安徽中源管业有限公司|安徽中源管业有限公司,安徽中源管业有限公司介绍,安徽中源管业有限公司电话,安徽中源管业有限公司地址,安徽中源管业有限公司厂家,安徽中源管业有限公司电力管,安徽中源管业有限公司管材
安徽中源管业有限公司
云南高职单招|云南单招,云南单招网,云南高职单招网,云南高职单招,云南单招学校,云南单招培训
云南高职单招
大理科技管理学校|大理科技管理学校,大理科技,大理科技中等职业技术学校,大理科技管理中等职业技术学校,大理科技学校
大理科技管理学校
大理科技管理学校|大理科技管理中等职业技术学校,大理市科技管理中等职业技术学校
大理科技管理学校
国家开放大学|国家开放大学报名,国家开放大学报考,国家开放大学,什么是国家开放大学,国家开放大学学历,国家开放大学学费,国家开放大学报名条件,国家开放大学报名时间,国家开放大学学历,国家开放大学专业
国家开放大学
安徽开放大学|安徽开放大学报名,安徽开放大学报考,安徽开放大学,什么是安徽开放大学,安徽开放大学学历,安徽开放大学学费,安徽开放大学报名条件,安徽开放大学报名时间,安徽开放大学学历,安徽开放大学专业
安徽开放大学
小程序开发|微信小程序,小程序开发,小程序,小程序制作,微信小程序开发,小程序公司,小程序开发公司,分销,三级分销系统,分销系统
小程序开发
中源管业|中源管业,中源管业公司,中源管业有限公司,中源管业电话,中源管业地址,中源管业电力管,中源管业mpp电力管,中源管业cpvc电力管,中源管业pe穿线管
中源管业

微信小程序

微信扫一扫体验

立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部