9

Preparing for the ZEND-Exam, I found a question where a class redefined the strlen-function:

namespace MyFramework\MyString
{
  function strlen ($str) 
  {
    return \strlen($str) * 2; // return double string-length
  }

}

I never came across that "\function"-thing before and could not get an explanation from my trainer - can somebody pls. help shed some light...?

Robin Bastiaan
  • 572
  • 2
  • 8
  • 21
MBaas
  • 7,248
  • 6
  • 44
  • 61

2 Answers2

8

It calls a function from the global namespace.

You need it only if there's a function of the same name in the current namespace.

holographic-principle
  • 19,688
  • 10
  • 46
  • 62
5

Introduced in PHP 5.3, \ is a namespace separator.

In your example, the outer strlen is MyFramework\MyString\strlen, the inner strlen is the global one.

Without any namespace definition, all class and function definitions are placed into the global space - as it was in PHP before namespaces were supported. Prefixing a name with \ will specify that the name is required from the global space even in the context of the namespace.

Reference: http://www.php.net/manual/en/language.namespaces.global.php

hakre
  • 193,403
  • 52
  • 435
  • 836
Lorenzo Marcon
  • 8,029
  • 5
  • 38
  • 63