How to check if a string can be used as a variable

2020-06-16 04:10发布

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?

7条回答
Juvenile、少年°
2楼-- · 2020-06-16 05:05

but I will not be able to access it with $object->...... because it would not parse correctly

but look:

class A {}

$varName = '!asd asd';
$a = new A();
$a->$varName = '1';
echo "{$a->{'!asd asd'}}"; // 1

Certainly not recommended but it can be done.

查看更多
登录 后发表回答