PHP手册中关于命名空间的这段解释是啥意思?

WBOY
Release: 2016-06-06 20:43:53
Original
812 people have browsed it

注意访问任意全局类、函数或常量,都可以使用完全限定名称,例如 \strlen() 或 \Exception 或 \INI_ALL。

<code class="lang-php">class APIConnectionException extends \Exception {
    public $isResponseTimeout;
    function __construct($message, $isResponseTimeout = false) {
        parent::__construct($message);
        $this->isResponseTimeout = $isResponseTimeout;
    }
}
</code>
Copy after login
Copy after login

这里的extends \Exception可以直接写成extends Exception吗?就是说系统的函数或者类既可以写成\Exception或者\strlen(),也可以写成Exception或者strlen()吗?
回答是或不是就可以了,如果要补充,欢迎补充哈!

回复内容:

注意访问任意全局类、函数或常量,都可以使用完全限定名称,例如 \strlen() 或 \Exception 或 \INI_ALL。

<code class="lang-php">class APIConnectionException extends \Exception {
    public $isResponseTimeout;
    function __construct($message, $isResponseTimeout = false) {
        parent::__construct($message);
        $this->isResponseTimeout = $isResponseTimeout;
    }
}
</code>
Copy after login
Copy after login

这里的extends \Exception可以直接写成extends Exception吗?就是说系统的函数或者类既可以写成\Exception或者\strlen(),也可以写成Exception或者strlen()吗?
回答是或不是就可以了,如果要补充,欢迎补充哈!

在你的这个例子里,答案是“是”

PHP对于没有指定命名空间的类或者函数会默认它的命名空间为当前的命名空间,而这段代码当前的命名空间为空,为空的情况就是根空间\,所以你写或者不写都对,因为他们指向的都是一个空间

如果你在类的前面声明一个命名空间

<code class="lang-php">namespace Some\Namespace;
</code>
Copy after login

就会有区别了,比如你把\Exception前面的反斜杠去掉,根据前面说的原则,当前的命名空间就变成了Some\Namespace,所以它会去找Some\Namespace\Exception,最后就会抛出你找不到的错误

Related labels:
php
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!