\(反斜杠)在PHP(5.3+)中做什么?

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

\在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
1个回答
222
投票

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

A \在函数开始之前表示Global Namespace

将其放在此处将确保所调用的函数来自全局名称空间,即使当前名称空间中存在相同名称的功能。


20
投票

为了澄清潜在的混乱:

反斜杠暗示类继承

以下,AnimalDogShepherd不必是类,而只是namespaces。用来将名称分组到avoid naming collisions的含义。

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

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


18
投票

命名空间

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

请参阅有关的官方文档namespacing

Opcache

另外,在PHP 7.0+中,某些功能由OPCache 替换为操作码,这使这些特定功能的运行速度大大提高。但是,这仅在将函数放置在根名称空间中时有效。有关此主题,请参见此discussion。因此,除了命名空间外,\还间接影响代码的优化。

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

"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"

9
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.