In PHP one can use variable variables...
For example...
class obj { }
$fieldName = "Surname";
$object = new obj();
$object->Name = "John";
$object->$fieldName = "Doe";
echo "{$object->Name} {$object->Surname}"; // This echoes "John Doe".
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.
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?
'[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*'
will validate a PHP variable name.This regex is directly from the documentation at: http://www.php.net/manual/en/language.variables.basics.php
From the manual:
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:Followed by this code example:
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.I think regex is the way to go, and as far as I can remember the restrictions are:
so the regex would be "/[a-zA-Z]+[0-9a-zA-Z_]*/" - off the top of my head so your milage may vary.
You will still be able to access the field through the
$object->{"fieldname"}
syntax.As far as I know, the only restriction is that you can't access properties with
\x00
in the name and you can't define variables starting with\x00
.Example:
As it was already replied, but not with a complete line of code:
Validating with RegEx if you wanted to allow
$
or&$
(pass variable by reference) to be validated in the string, you could use this regex: