编程

PHP 8.3: 新增 stream_context_set_options 函数

334 2023-10-29 20:42:00

PHP 有一个 stream_context_set_option 函数,支持两种函数签名。它可以接受为一个或者多个 context/wrapper 设置的一个 options 数组;也可以接受一个单一的 wrapper 名,选项名,及其选项值。

function stream_context_set_option($stream_or_context, string $wrapper, string $option, mixed $value): bool {}

function stream_context_set_option($stream_or_context, array $options): bool {}

作为 PHP 删除重载函数签名(支持多个签名的函数)工作的一部分,PHP 8.3 声明了一个新函数 steam_context_set_options (注意最后一个 ”s“) 支持上面的第二个签名。

在 PHP 8.4 中,stream_context_set_option($stream_or_context, string $wrapper, string $option, mixed $value) 签名将被启用,而 PHP 9.0 将移除 stream_context_set_option 函数。

新增 stream_context_set_options 函数

/**
 * @param resource $context The stream or context resource to apply the options to
 * @param array $options The options to set for `stream_or_context`
 * @return bool Returns true success or false on failure.
 */
function stream_context_set_options($context, array $options): bool {}

stream_context_set_options polyfill

在 PHP 8.2 及之前的版本中,可以手动实现 stream_context_set_options 函数:

if (\PHP_VERSION_ID < 80300) {
    /**
     * @param resource $context The stream or context resource to apply the options to
     * @param array $options The options to set for `stream_or_context`
     * @return bool Returns true success or false on failure.
     */
    function stream_context_set_options($context, array $options): bool {
        return \stream_context_set_option($context, $options);
    }
}

该 polyfill 仅仅声明了一个新的 stream_context_set_options 函数,并调用现有的 stream_context_set_option 函数,使用它支持的第二个签名。

向后兼容性影响

除非在用户空间中已经声明了 stream_context_set_options 函数,PHP 应用中引入该函数不会有兼容性问题。

这个新增的 stream_context_set_options 函数可以在老版本中 polyfill 打补丁。