Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

PHP PHP User Authentication Building the Library Adding Books

Why do we need \ in front of Exception in the try catch block?

In previous videos I don't recall Alena putting a "\" in front of the Exception in (Exception $e) but in this course she does. I just wondered why?

1 Answer

Michael Cook
Michael Cook
596 Points

The backslashes are like a file path or a website address. Each backslash represents another level deep in a nested hierarchy. When you reference a class within the scope of a namespace, the autoloader is going to think that the class you are referencing can be found somewhere in your namespace hierarchy. So if you make reference to Exception within a namespaced class, PHP will (wrongly) think that it is part of the current namespace, and it will result in an error. The problem is, Exception is a built-in PHP class and doesn't have a namespace.

But, if you either use the Exception class at the top of your file, or reference it as \Exception then PHP will know that it is a core PHP class and isn't part of your namespace hierarchy. The prepended backslash is like the equivalent of referencing a file at the root of a directory with ./.

I hope this makes sense. I attempted to explain it in my own words so solidify my understanding, but in case it wasn't clear enough here's a video that explains PHP namespaces: https://symfonycasts.com/screencast/php-namespaces/namespaces

Thanks Michael! That video cleared it up for me.