phplaravel

Difference between (Exception $e) and (\Exception $e)


What is the difference between (Exception $e) and (\Exception $e)

Case 1

try{

} catch(Exception $e) {

}

Case 2

try{

} catch(\Exception $e) {

}

Solution

  • 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