您可以在 PHP 名称中为变量、常量、函数、方法、类...使用哪些有效字符?
手册有some mentions的正则表达式 [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*
。此限制何时适用,何时不适用?
最佳答案
[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*
正则表达式仅适用于在某些特殊情况下直接使用名称的情况语法元素。一些例子:
$varName // <-- varName needs to satisfy the regex
$foo->propertyName // <-- propertyName needs to satisfy the regex
class ClassName {} // <-- ClassName needs to satisfy the regex
// and can't be a reserved keyword
请注意,此正则表达式是逐字节应用的,未考虑编码。这就是为什么它也是 allows many weird Unicode names .
但是正则表达式仅限制名称的这些“直接”使用。通过 PHP 提供的各种动态特性,几乎可以使用任意名称。
一般来说,您不应假设 PHP 中可以包含哪些字符名称。在大多数情况下,它们只是任意字符串。在 PHP 中做诸如“验证某物是否为有效类名”之类的事情毫无意义。
在下文中,我将举例说明如何为不同的类别创建奇怪的名称。
变量
变量名可以是任意字符串:
${''} = 'foo';
echo ${''}; // foo
${"\0"} = 'bar';
echo ${"\0"}; // bar
常量
全局常量也可以是任意字符串:
define('', 'foo');
echo constant(''); // foo
define("\0", 'bar');
echo constant("\0"); // bar
没有办法动态定义我所知道的类常量,所以这些不能是任意的。创建奇怪的类常量的唯一方法似乎是通过扩展代码。
属性
属性不能是空字符串,不能以NUL字节开头,但除此之外它们是任意的:
$obj = new stdClass;
$obj->{''} = 'foo'; // Fatal error: Cannot access empty property
$obj->{"\0"} = 'foo'; // Fatal error: Cannot access property started with '\0'
$obj->{'*'} = 'foo';
echo $obj->{'*'}; // foo
方法
方法名是任意的,可以通过__call
magic 处理:
class Test {
public function __call($method, $args) {
echo "Called method \"$method\"";
}
}
$obj = new Test;
$obj->{''}(); // Called method ""
$obj->{"\0"}(); // Called method "\0"
类
可以使用 class_alias
创建任意类名,空字符串除外:
class Test {}
class_alias('Test', '');
$className = '';
$obj = new $className; // Fatal error: Class '' not found
class_alias('Test', "\0");
$className = "\0";
$obj = new $className; // Works!
函数
我不知道有什么方法可以从用户区创建任意函数名称,但在某些情况下内部代码会产生“奇怪”的名称:
var_dump(create_function('',''));
// string(9) "\0lambda_1"
关于php - PHP 变量、方法、类等名称中的有效字符是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17973357/