Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialHannah Myers
12,149 PointsWhy 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
2,125 PointsThe 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
Hannah Myers
12,149 PointsHannah Myers
12,149 PointsThanks Michael! That video cleared it up for me.