\在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 5.3中的命名空间分隔符。

函数开头前的\表示全局命名空间。

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


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


为了澄清可能的混淆:

反斜杠并不意味着类继承。

在下面的例子中,Animal、Dog、Shepherd不一定是类,而只是名称空间。意思是用来将名称组合在一起以避免命名冲突的东西。

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

在全球范围内宣布领先的动物。


名称空间

在PHP 5.3+中,反斜杠\符号用于命名空间。它是指示名称空间的开始符号,也用作子名称空间名称之间的分隔符。

参见有关的官方文档 命名空间。

操作缓存

此外,在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"