$ this - >"变量值"OOP PHP

mrG*_*ott 4 php

我想知道它是否可能,如果是的话,我怎么会这样做:

$this->id < - 我有这样的事情.但为了让它更有用我想拥有$this->(and here to change the values)

对于前:我可能有 $this->id $this->allID $this->proj_id

我怎么能这样做,实际上我有$this->($myvariable here, that has a unique name in it)

Gor*_*dyD 8

你可以简单地使用这个:

 $variable = 'id';
 if ( isset ( $this->{$variable} )  ) 
 {
    echo $this->{$variable};
 }
Run Code Online (Sandbox Code Playgroud)

  • 我会使用$ this - > {$ variable}以防万一$ variable计算到包含连字符的内容.$ this-> some-thing不是一个有效的表达式,而$ this - > {'some-thing'}可以正常工作. (3认同)
  • 再次,$ this - > {$ variable}更好的恕我直言.在您的解决方案中,第二个美元符号很容易被忽视. (2认同)