Hi. I have a question: Is there a formal rule in PHP standard library that any function which returns false as a mean to signify a failure does also issue a warning?

In many codebases warnings are converted to an exception by means of set_error_handler().

Example 1
------------------------------------------------------------------
set_error_handler(fn($_, $s) => throw new \RuntimeException($s));

if (false === mkdir('/doesn/t/exist/dir')) {
    throw new \RuntimeException("can't mkdir");
}
------------------------------------------------------------------

The above code confuses a reader with issues 1) isn't the only possible return value is now true? 2) if it throws on failure, then how can it return anything?

One may say the checking for false return value is redundant and the above version can be simplified based on premise that mkdir() emits warning in _all_ cases where it is about to return false.

Example 2
------------------------------------------------------------------
set_error_handler(fn($_, $s) => throw new \RuntimeException($s));

mkdir('/doesn/t/exist/dir');
------------------------------------------------------------------

But there is also a possibility that a built-in function fails, returns false but doesn't issue any warning, therefore the handler set with set_error_handler() doesn't get called and execution continues erroneously contrary to the programmer intend of it being halted.

Looking at mkdir() documentation I can't find the language supporting assumption made in Example 2.

The page lists two cases for which warnings are raised: "directory already exists" and "relevant permissions prevent creating the directory". Does it mean that in case of "No such file or directory" the function would return false without raising a warning? It is possible as documentation never stated mkdir() would emit warning on _any_ failure, just return false.

One may add a unit-test against mkdir() to the one's project codebase proving that "Warning: mkdir(): No such file or directory" is raised too, despite not being listed in documentation.  So far we have three cases covered. But obviously this doesn't prove that a warning would be raised for all failures, thus doesn't allow us to deem Example 2 correct and replace Example 1 with it.

Is relying on warnings being converted to exceptions by error handler is equivalent to checking return value with regards to the set of error conditions covered? If this guarantee is already there, please point to me to the relevant documentation page.

--
PHP Internals - PHP Runtime Development Mailing List
To unsubscribe, visit: https://www.php.net/unsub.php

Reply via email to