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

前端 未结 7 1600
孤独总比滥情好
孤独总比滥情好 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

    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.

    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:

    $a = new stdclass;
    $a->{"\x00dd"} = 8; //invalid
    $a->{"dd\x00dd"} = 8; //valid, but...
    echo $a->{"dd\x00dd"}; //can't read (no property "dd")
    

提交回复
热议问题