How do I access a PHP object attribute having a dollar sign?

后端 未结 5 2092
清歌不尽
清歌不尽 2020-11-29 12:17

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-         


        
相关标签:
5条回答
  • 2020-11-29 12:39

    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');

    0 讨论(0)
  • 2020-11-29 12:42
    1. With variable variables:

      $myVar = 'variable$WithDollar';
      echo $object->$myVar;
      
    2. With curly brackets:

      echo $object->{'variable$WithDollar'};
      
    0 讨论(0)
  • 2020-11-29 12:44

    I assume you want to access properties with variable names on the fly. For that, try

    echo $object->{"variable".$yourVariable}
    
    0 讨论(0)
  • 2020-11-29 12:44

    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.

    0 讨论(0)
  • 2020-11-29 12:47

    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.

    0 讨论(0)
提交回复
热议问题