对非数字字符串进行自增已弃用,请改用str_increment()
我们正在将一个遗留的PHP应用迁移到PHP 8.5。我们还必须支持较旧的PHP版本,也就是在PHP 8.3之前的版本。
我有一段代码试图用一个字母对一个变量进行自增:
$d = 'H';
++$d;
这在PHP 8.5中会产生弃用警告
已弃用:对非数字字符串进行自增已不再被推荐,请使用str_increment()。
然而,这个函数在PHP < 8.3中不可用。我们该如何重写代码,使其在所有PHP 8的版本上都能工作?
解决方案
该弃用警告是在PHP 8.5中引入的,自PHP 8.3.0起就有替代方案: str_increment():
$d = 'H';
$d = str_increment($d);
还有 str_decrement()。
如果你需要编写的代码也能在8.3之前的版本上工作,你可以要么写一个自定义包装函数来进行PHP版本检测,要么更好地,编写一个polyfill。你在其他回答中也能看到一些例子。
为确保完整性,Symfony提供了一个你可以直接使用或从中获得灵感的实现:symfony/polyfill-php83。
要按原样使用它,只需通过Composer加载该包。无需其他步骤。
相关源代码可在 https://github.com/symfony/polyfill-php83/blob/v1.33.0/Php83.php#L87-L125 找到:
public static function str_increment(string $string): string
{
if ('' === $string) {
throw new \ValueError('str_increment(): Argument #1 ($string) cannot be empty');
}
if (!preg_match('/^[a-zA-Z0-9]+$/', $string)) {
throw new \ValueError('str_increment(): Argument #1 ($string) must be composed only of alphanumeric ASCII characters');
}
if (is_numeric($string)) {
$offset = stripos($string, 'e');
if (false !== $offset) {
$char = $string[$offset];
++$char;
$string[$offset] = $char;
++$string;
switch ($string[$offset]) {
case 'f':
$string[$offset] = 'e';
break;
case 'F':
$string[$offset] = 'E';
break;
case 'g':
$string[$offset] = 'f';
break;
case 'G':
$string[$offset] = 'F';
break;
}
return $string;
}
}
return ++$string;
}
...,其加载方式如下:
use Symfony\Polyfill\Php83 as p;
if (\PHP_VERSION_ID >= 80300) {
return;
}
if (!function_exists('str_increment')) {
function str_increment(string $string): string { return p\Php83::str_increment($string); }
}
if (!function_exists('str_decrement')) {
function str_decrement(string $string): string { return p\Php83::str_decrement($string); }
}
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。