41

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,738
  • 21
  • 105
  • 131
Kyle Cureau
  • 19,028
  • 23
  • 75
  • 104

3 Answers3

35

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ashurexm
  • 6,209
  • 3
  • 45
  • 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
  • 356,200
  • 43
  • 426
  • 500
  • 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
  • 15
    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,209
  • 3
  • 45
  • 69
Konrad Borowski
  • 11,584
  • 3
  • 57
  • 71