Categories


Archives


Recent Posts


Categories


PHP Namespaces and Exceptions

astorm

Frustrated by Magento? Then you’ll love Commerce Bug, the must have debugging extension for anyone using Magento. Whether you’re just starting out or you’re a seasoned pro, Commerce Bug will save you and your team hours everyday. Grab a copy and start working with Magento instead of against it.

Updated for Magento 2! No Frills Magento Layout is the only Magento front end book you'll ever need. Get your copy today!

If you’re working in a PHP file that’s namespaced, and you’ve setup a simple try/catch block like this

try
{
    //do something that might throw an exception
}
catch(Exception $e)
{
    echo "Caught you!";
}

You may be surprised when your program doesn’t catch the thrown exception. That’s because Exceptions are classes, and the Exception class exists in the global namespace. That means you need to catch it with a leading backslash.

catch(Exception $e)
{
    echo "Caught you!";
}

In java, the Exception in front of the $e is a type declaration. Since PHP doesn’t have type declarations, their borrowing of this syntax has led to many developers (i.e. me) to think of Exception $e as magic boilerplate, instead of an actual type hint.

Not strictly Magento 2 related, but it seems worth mentioning since Magento 2 will be a lot of developer’s first deep dive into PHP namespaces.

Copyright © Alan Storm 1975 – 2019 All Rights Reserved

Originally Posted: 6th December 2013