\(反斜杠)在 PHP (5.3+) 中有何作用?

问题描述 投票:0回答:5

\
在 PHP 中起什么作用?

例如,CSRF4PHP

\FALSE
\session_id
\Exception

public function __construct($timeout=300, $acceptGet=\FALSE){
    $this->timeout = $timeout;
    if (\session_id()) {
        $this->acceptGet = (bool) $acceptGet;
    } else {
        throw new \Exception('Could not find session id', 1);
    }
}
php namespaces opcode opcache
5个回答
337
投票

\
(反斜杠)是 PHP 5.3 中的命名空间分隔符。

函数开头之前的

\
代表全局命名空间

将其放在那里将确保调用的函数来自全局命名空间,即使当前命名空间中存在同名函数。


40
投票

命名空间

在 PHP 5.3+ 中,反斜杠

\
符号用于命名空间。它是指示名称空间的开始符号,也用作子名称空间名称之间的分隔符。

查看官方文档 命名空间

Opcache

此外,在 PHP 7.0+ 中,一些函数被 OPCache 替换为操作码,这使得这些特定函数的运行速度更快。然而,这只在函数放置在根命名空间中时才有效。请参阅有关此主题的讨论。因此,除了命名空间之外,

\
也会间接影响代码优化。

以下本机函数受益于此效果:

"array_slice"
"assert"
"boolval"
"call_user_func"
"call_user_func_array"
"chr"
"count"
"defined"
"doubleval"
"floatval"
"func_get_args"
"func_num_args"
"get_called_class"
"get_class"
"gettype"
"in_array"
"intval"
"is_array"
"is_bool"
"is_double"
"is_float"
"is_int"
"is_integer"
"is_long"
"is_null"
"is_object"
"is_real"
"is_resource"
"is_string"
"ord"
"strlen"
"strval"

33
投票

为了澄清潜在的混乱:

反斜杠并不暗示类继承

在下文中,

Animal
Dog
Shepherd
不一定是类,而只是命名空间。意思是用来将名称分组在一起的东西避免命名冲突

$myDog = new \Animal\Dog\Shepherd\GermanShepherd();

前导

\
表示
Animal
已在全局范围内声明。


10
投票

\
在 PHP 5.3 中用于命名空间。有关命名空间和 PHP 的更多信息,请参阅 http://www.php.net/manual/en/language.namespaces.rationale.php


0
投票
除了

Webber的回答之外,以下本机函数也受益于Opcache代码优化(参考):

"function_exists" "is_callable" "extension_loaded" "dirname" "constant" "define"
    
© www.soinside.com 2019 - 2024. All rights reserved.