Reputation: 13406
I'm writing a lot of code like this in a few of my functions :
$f = fopen($fname);
if ($f === false) {
throw new Exception("cannot open $fname");
}
This is verbose when you deal with a lot of file to open & deal with. I'm wondering if this can work without any unforeseen bad side-effect :
$f = fopen($fname) or die("cannot open $fname");
This is idiomatic in Perl, but is this correct in PHP ? Is there another, better way to do it ? It seems valid, but I know PHP can bite you in a lot of unexpected ways.
Upvotes: 0
Views: 53
Reputation: 39356
I tend to opt for something like:
if(!($f = @fopen($fname, 'r'))) {
throw new Exception("cannot open $fname");
}
The perl-style is fine too, although I believe fopen will raise errors.
Upvotes: 1
Reputation: 59997
Personally I make all the code as a function that can possibly throw an exception. Then call that function catching exceptions. Upon receipt of an exception if it is the live (production) generate an appropriate page and log details. Otherwise (testing/development) put those details onto the page.
Upvotes: 1