问题描述
在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?
推荐答案
来自手册:
因此,如果您通过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
文档:
下面的代码示例:
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中用作变量名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!