Using Partial Function Application to define stricter functions
I was at the Forum PHP in Paris last week, and came up with a use case for PHP 8.6's PFA feature:
using them to declare strict versions of built-in function that expose a
$strict parameter.
For example one could declare const in_array_strict = in_array(?, ?, true);
and then use some project wide rules to ban the use of in_array()
and instead require the usage of in_array_strict.
One major annoyance with this idea is that to actually call the constant one needs to write the call as:
(in_array_strict)($needle, $haystack) so that in_array_strict is properly fetched
as a constant and not as a function name that does not exist.
This wouldn't be an issue if PHP had a unique symbol table for constants/functions/classes,
alas merging them is not an easy task as one would first need to make functions and classes case-sensitive.
The other thing to keep in mind is that PFAs use the INIT_DYNAMIC_CALL opcode to initialise
a call rather than the INIT_FCALL one. This might have performance
implications, especially for in_array() as it has a frameless variant that
uses the FRAMELESS_ICALL_{2|3} opcode variant.
However, it should be possible to improve PHP's optimiser to use "better" opcodes if the PFA is known.
Something to keep an eye on for PHP 8.7. :)
This technique could also be used for functions that expose a int $flags
parameter such as json_decode() and define a version with predetermined flags
that should always be used within your project
(e.g. JSON_BIGINT_AS_STRING | JSON_INVALID_UTF8_SUBSTITUTE | JSON_THROW_ON_ERROR).
It will be interesting to see if this pattern will spread to actual codebases or will remain an interesting curiosity.