如何检查字符串是否可以在PHP中用作变量名? [英] How to check if a string can be used as a variable name in PHP?

查看:217
本文介绍了如何检查字符串是否可以在PHP中用作变量名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In PHP one can use variable variables...

例如...

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-> ......访问它,因为它将无法正确解析.

However, $fieldName string may contain some characters not allowed in variable names. PHP will still create the field with that name (much like the associative array), but I will not be able to access it with $object->...... because it would not parse correctly.

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

Now, is there any function that can check if the string can be used as a valid PHP variable name. If not, how would this be created using regular expressions? What are the rules for variable names in PHP?

推荐答案

来自手册:

变量名称与PHP中的其他标签遵循相同的规则.有效的变量名称以字母或下划线开头,后跟任意数量的字母,数字或下划线.作为正则表达式,它将表示为:'[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*'

因此,如果您通过RegEx运行字符串,则应该能够知道它是否有效.

So If you ran your string through the RegEx, you should be able to tell if it's valid or not.

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

It should be noted that the ability to access 'invalid' Object property names using a variable variable is the correct approach for some XML parsing.

例如,来自SimpleXML文档:

访问XML文档中包含PHP命名约定不允许的字符的元素(例如,连字符)可以通过将元素名称封装在花括号和撇号中来实现.

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;

因此拥有只能以这种方式访问​​的属性并不一定是错误.

So it's not necessarily wrong to have properties that can only be accessed this way.

但是,如果您的代码同时创建并使用了该对象,那么您会想知道为什么要使用这种类型的属性.当然,允许类似SimpleXML示例的情况,在该示例中创建了一个对象来表示超出控件范围的对象.

However, if your code both creates and uses the object - one would wonder why you would use those kind of properties. Allowing, of course, a situation similar to the SimpleXML example, where an object is created to represent something outside the scope of your control.

这篇关于如何检查字符串是否可以在PHP中用作变量名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆