40

I just saw the use of a backslash in a reference to a PHP object and was curious about it (I have never seen this before). What does it mean?

$mail = new SendGrid\Mail();

If you're curious, here's SendGrid's documentation.

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
Kyle Cureau
  • 18,281
  • 23
  • 70
  • 100

3 Answers3

34

It's because they're using PHP namespaces. Namespaces are new as of PHP 5.3.

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
ashurexm
  • 6,111
  • 3
  • 44
  • 69
19

It's PHP's namespace operator: http://php.net/manual/en/language.namespaces.php.

Don't ask why it's a backslash. It's (imho) the stupidest possible choice they could have made, basing their decisions on a highly slanted/bigoted scoring system that made sense only to the devs.

Marc B
  • 348,685
  • 41
  • 398
  • 480
  • 2
    Well, backslash was best available choice (would you want to use `:::` or `->->`?). – Konrad Borowski May 28 '12 at 17:33
  • That could work too, but `->Hello->something()` would look ugly. And I don't think PHP would like having operator mean two things at once (especially so different, when I would see `Abc->def()` for first time I would think it's method of constant `Abc`). – Konrad Borowski May 28 '12 at 17:37
  • 14
    They shouldn't have used the dot operator for string concat, what a waste for a good namespace operator! – James Lin Jun 22 '13 at 21:24
  • 7
    Check RFC https://wiki.php.net/rfc/namespaceseparator for how they chose Backslash. – Bijay Rungta Aug 29 '13 at 13:50
  • I'm so going to create an `n` namespace! But seriously... if you can separate folders and files with `/`, why not separate namespaces and classes with `::`? – Erk Nov 10 '16 at 06:23
9

This is syntax for namespaces. You can read more about namespaces at PHP documentation. They they require at least PHP 5.3.

For example:

namespace SendGrid;
function Mail() {
    // You can access this function by using SendGrid\Mail() externally
}
ashurexm
  • 6,111
  • 3
  • 44
  • 69
Konrad Borowski
  • 10,745
  • 3
  • 55
  • 71