且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-11-07 18:21:28

来自手册:

变量名称与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.