[英]What does a \ (backslash) do in PHP (5.3+)?
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 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"
澄清潜在的混淆:
反斜杠并不意味着类继承。
在下面, Animal
, Dog
, Shepherd
不必是类,而只是namespaces 。 意思是用于将名称组合在一起以避免命名冲突的东西。
$myDog = new \Animal\Dog\Shepherd\GermanShepherd();
领先的\\
表示Animal
是在全局范围内声明的。
\\
在 PHP 5.3 中用于命名空间。 有关名称空间和 PHP 的更多信息,请参阅http://www.php.net/manual/en/language.namespaces.rationale.php 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.