How to check if a string can be used as a variable name in PHP?

前端 未结 7 1609
孤独总比滥情好
孤独总比滥情好 2021-02-15 18:08

In PHP one can use variable variables...

For example...

class obj { }
$fieldName = \"Surname\";
$object = new obj();
$object->Name = \"John\";
$objec         


        
7条回答
  •  既然无缘
    2021-02-15 18:42

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

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

    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.

    For example, from the SimpleXML docs:

    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.

    Followed by this code example:

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

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

    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.

提交回复
热议问题