php - 如何检查字符串是否可以用作 PHP 中的变量名?

标签 php variables object names variable-variables

在 PHP 中可以使用可变变量...

例如……

class obj { }
$fieldName = "Surname";
$object = new obj();
$object->Name = "John";
$object->$fieldName = "Doe";
echo "{$object->Name} {$object->Surname}"; // This echoes "John Doe".

但是,$fieldName 字符串可能包含一些不允许出现在变量名中的字符。 PHP 仍将创建具有该名称的字段(很像关联数组),但我将无法使用 $object->...... 访问它,因为它无法正确解析。

现在,是否有任何函数可以检查字符串是否可以用作有效的 PHP 变量名。如果没有,这将如何使用正则表达式创建? PHP 中变量名的规则是什么?

最佳答案

来自 the manual :

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]*'

因此,如果您通过 RegEx 运行您的字符串,您应该能够判断它是否有效。

应该注意的是,使用可变变量访问“无效”对象属性名称的能力是某些 XML 解析的正确方法。

例如,来自 SimpleXML 文档:

Accessing elements within an XML document that contain characters not permitted under PHP's naming convention (e.g. the hyphen) can be accomplished by encapsulating the element name within braces and the apostrophe.

后面是这个代码示例:

echo $xml->movie->{'great-lines'}->line;

因此拥有只能通过这种方式访问​​的属性不一定错误

但是,如果您的代码既创建又使用该对象 - 人们会想知道您为什么要使用这些类型的属性。当然,允许出现类似于 SimpleXML 示例的情况,其中创建一个对象来表示您控制范围之外的事物。

关于php - 如何检查字符串是否可以用作 PHP 中的变量名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3980154/

相关文章:

WPF:如何将对象绑定(bind)到组合框

php - 如何将变量从php模板传递给javascript

php - sql表排列

Java - 为什么将 F 附加到 `float a=0.32F` 告诉它在 a 中存储 32 位 float ,但执行 `float a = 0.32` 却告诉它你想存储 64 位 double ?

PHP 全局或 $GLOBALS

c# - 我可以将包含对象的列表转换为二维数组吗

javascript - 更改 td 内容以选择,反之亦然

php - 如何在php中使用 'Curl'向android发送数据

c++ - 在 C++ 中的三个不同函数中从一个文件访问三个不同的变量

javascript - Lodash uniqWith,怎么说lodash keep last duplicate