为什么提取不导入负指数?

Why extract doesn't import negative indices?

我在玩提取方法,我注意到它不适用于负索引。

我们以这段代码为例:

<?php

$arr = [0 => 'faa', 1 => 'fee', -2 => 'foo'];
$result = extract($arr, EXTR_PREFIX_INVALID, 'var');

echo $var_-2; // Absolutely wrong

?>

所以我尝试这样做:

echo ${'var_-2'} // Notice: Undefined variable: var_-2

然后根据文档提取 here

Returns the number of variables successfully imported into the symbol table

我这样做了:

echo $result; // 2

似乎提取物并没有首先将 -2 导入到符号 table 中。

由于文档未提及此行为,具体原因是什么?

因为 - 根据 php variable naming conventions 不是有效符号。

从文档中厚颜无耻地复制了以下引述:

Variable names follow the same rules as other labels in PHP. A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus: '[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*'

// var_-2 results in 0 because of -
var_dump(preg_match("/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/", "var_-2")); // int(0)
// var_2 is a valid identifier so result is 1
var_dump(preg_match("/^[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*$/", "var_2")); // int(1)