5

What is the difference between (Exception $e) and (\Exception $e) in try{}catch(){}
What is the impact of 'back-slash \' before Exception?

viraptor
  • 33,322
  • 10
  • 107
  • 191
Hasib Kamal Chowdhury
  • 2,476
  • 26
  • 28

2 Answers2

11

Using \ in front of class name, it mean you call the class from global space. If you don't use \, it will call the class in same namespace with your code. But if you don't use namespace in your code, it will call class from global space.

Example:

<?php
namespace Module\Example;

class Test
{
    try{

    } catch(Exception $e) { // will look up Module\Example\Exception

    }

    try{

    } catch(\Exception $e) { // will look up Exception from global space

    }
}

You can check this documentation for more detail. http://php.net/manual/en/language.namespaces.global.php

Dolly Aswin
  • 2,684
  • 1
  • 20
  • 23
1

Back slash like this \Exception represents Global namespace. It specifies that the functions in the class are called from global namespace and it will not overwrite the function with same name within the same namespace.

According to php.net -

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.

Rudraksh Pathak
  • 888
  • 8
  • 20