How do I access a PHP object attribute having a dollar sign?
I have a PHP Object with an attribute having a dollar ($) sign in it.
How do I access the content of this attribute ?
Example :
echo $object->开发者_开发技巧;variable; // Ok
echo $object->variable$WithDollar; // Syntax error :-(
With variable variables:
$myVar = 'variable$WithDollar'; echo $object->$myVar;
With curly brackets:
echo $object->{'variable$WithDollar'};
Thanks to your answers, I just found out how I can do that the way I intended :
echo $object->{'variable$WithDollar'}; // works !
I was pretty sure I tried every combination possible before.
I assume you want to access properties with variable names on the fly. For that, try
echo $object->{"variable".$yourVariable}
You don't.
The dollar sign has a special significance in PHP. Although it is possible to bypass the variable substitution in dereferencing class/object properties you NEVER should be doing this.
Don't try to declare variables with a literal '$'.
If you're having to deal with someoneelse's mess - first fix the code they wrote to remove the dollars then go and chop off their fingers.
C.
There are reflection methods that also allow you to construct method and attribute names that may be built by variables or contain special characters. You can use the ReflectionClass::getProperty ( string $name ) method.
$object->getProperty('variable$WithDollar');
精彩评论