Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is better in PHP: suppress warnings with '@' or run extra checks with isset()?

Tags:

php

isset

For example, if I implement some simple object caching, which method is faster?

1. return isset($cache[$cls]) ? $cache[$cls] : $cache[$cls] = new $cls;

2. return @$cache[$cls] ?: $cache[$cls] = new $cls;

I read somewhere @ takes significant time to execute (and I wonder why), especially when warnings/notices are actually being issued and suppressed. isset() on the other hand means an extra hash lookup. So which is better and why?

I do want to keep E_NOTICE on globally, both on dev and production servers.

like image 612
mojuba Avatar asked Oct 04 '12 18:10

mojuba


People also ask

How do I suppress a warning in PHP?

Open PHP configuration file using your preferred text editor. Search for display_error directive. Set the value to Off if you don't want to see any error or warning messages at all. Set the value to On instead to further tune the types of messages to display using error_reporting directive.

How do I supress PHP errors?

PHP supports the @ error control operator (also called STFU operator with mixed feelings), that suppresses errors just for the expression that immediately follows. For example, the unlink function emits a warning if the file does not exist, and calling it with the @ operator can suppress these errors.


1 Answers

I wouldn't worry about which method is FASTER. That is a micro-optimization. I would worry more about which is more readable code and better coding practice.

I would certainly prefer your first option over the second, as your intent is much clearer. Also, best to keep away edge condition problems by always explicitly testing variables to make sure you are getting what you are expecting to get. For example, what if the class stored in $cache[$cls] is not of type $cls?

Personally, if I typically would not expect the index on $cache to be unset, then I would also put error handling in there rather than using ternary operations. If I could reasonably expect that that index would be unset on a regular basis, then I would make class $cls behave as a singleton and have your code be something like

return $cls::get_instance();
like image 164
Mike Brant Avatar answered Nov 15 '22 17:11

Mike Brant