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

PhpNamespacesOpcodeOpcache

Php Problem Overview


What does a \ do in PHP?

For example, CSRF4PHP has \FALSE, \session_id, and \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 Solutions


Solution 1 - Php

\ (backslash) is the namespace separator in 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.

Solution 2 - Php

Namespaces

In PHP 5.3+ the backslash \ symbol is used in namespaces. 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. 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"

Solution 3 - Php

To clarify potential confusion:

The backslash does not imply class inheritance.

In the following, Animal, Dog, Shepherd don't have to be classes, but simply 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.

Solution 4 - Php

The \ is used in PHP 5.3 for namespaces. See http://www.php.net/manual/en/language.namespaces.rationale.php for more information on namespaces and PHP.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlfredView Question on Stackoverflow
Solution 1 - PhpAlan GeleynseView Answer on Stackoverflow
Solution 2 - PhpWebberView Answer on Stackoverflow
Solution 3 - PhpNeluView Answer on Stackoverflow
Solution 4 - PhpDamian GalarzaView Answer on Stackoverflow