|
|
|
|
|
by arp242
778 days ago
|
|
The main problem with PHP 5 was never the lack of features, but things like "there is no way I can get an error code from fopen()", and things like that. Can I now get EEXISTS and such out of fopen()? Looking at the docs it still just returns false and emits an uncatchable E_WARNING that can't be examined programmatically. Having to write a bit more code because it doesn't have some feature is not ideal, but whatever. Not able to correctly race-free implement file access is a much bigger issue. I have some other gripes (which may or may not be fixed), but this was and remains my main one. |
|
Sure, the most straightforward way is to first use the "x" flag for write-only, and "x+" for read/write access.
From the PHP docs:"If the file already exists, the fopen() call will fail by returning false and generating an error of level E_WARNING. If the file does not exist, attempt to create it. This is equivalent to specifying O_EXCL|O_CREAT flags for the underlying open(2) system call."
And finally to convert E_WARNING errors to exceptions, use you can use set_error_handler() to throw an exception (and even write business logic to filter them): https://www.php.net/manual/en/language.exceptions.php
They're not unhandleable.
But if you want a single function that throws a specific exception when a file exists, specific to the behavior you want, I got you:
To run this code from outside a namespace, simply: Throw it in a library somewhere, having written it once, and now you can just use that whenever you want that behavior in your PHP code.