简体   繁体   English

PHP (5.3+) 中的 \(反斜杠)有什么作用?

[英]What does a \ (backslash) do in PHP (5.3+)?

What does a \ do in PHP? PHP 中的\有什么作用?

For example, CSRF4PHP has \FALSE , \session_id , and \Exception :例如, 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);
    }
}

\\ (backslash) is the namespace separator in PHP 5.3. \\ (反斜杠)是 PHP 5.3 中的命名空间分隔符。

A \\ before the beginning of a function represents the Global Namespace .函数开始前的\\代表全局命名空间

Putting it there will ensure that the function called is from the global namespace, even if there is a function by the same name in the current namespace.将它放在那里将确保调用的函数来自全局命名空间,即使当前命名空间中存在同名的函数。

Namespaces命名空间

In PHP 5.3+ the backslash \\ symbol is used in namespaces.在 PHP 5.3+ 中,反斜杠\\符号用于命名空间。 It is the start symbol to indicate a namespace and also serves as a separator between sub-namespace names.它是指示命名空间的开始符号,也用作子命名空间名称之间的分隔符。

See official documentation about namespacing .请参阅有关命名空间的官方文档。

Opcache缓存

Additionally in PHP 7.0+ some functions are replaced with opcodes by OPCache , which makes these specific functions run a lot faster.此外,在 PHP 7.0+ 中,一些函数被OPCache替换为操作码,这使得这些特定函数运行得更快。 However this only works when the functions are placed in the root namespace.然而,这只适用于将函数放置在根命名空间中的情况。 See this discussion about this topic.看到这个讨论这个话题。 So besides namespacing, the \\ indirectly also affects code optimisation.因此,除了命名空间之外, \\还会间接影响代码优化。

The following native functions benefit from this effect:以下本机函数受益于此效果:

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

To clarify potential confusion:澄清潜在的混淆:

The backslash does not imply class inheritance .反斜杠并不意味着类继承

In the following, Animal , Dog , Shepherd don't have to be classes, but simplynamespaces .在下面, AnimalDogShepherd不必是类,而只是namespaces Meaning something used to group names together to avoid naming collisions .意思是用于将名称组合在一起以避免命名冲突的东西

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

The leading \\ means Animal was declared in the global scope.领先的\\表示Animal是在全局范围内声明的。

The \\ is used in PHP 5.3 for namespaces. \\在 PHP 5.3 中用于命名空间。 See http://www.php.net/manual/en/language.namespaces.rationale.php for more information on namespaces and PHP.有关名称空间和 PHP 的更多信息,请参阅http://www.php.net/manual/en/language.namespaces.rationale.php

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM