访问名称在另一个属性中的属性


Access property whose name is in another property

我有一个动态包装所有数据库表的类:

class Table
{
  public $pk;
  ...
}
$Table=new Table();
$Table->pk='username'; //here I set what is PK column in my table
$Table->$pk='sbrbot'; //here I dynamically define variable and set $Table->username='sbrbot'

问题是,当我想从类中检索这个值时,我必须分两步到达它;

class Table
{
  ...
  $pk=$this->pk;
  $value=$this->$pk;
}

为什么:

$value=${$this->pk}

不起作用?

应该是:

$value = $this->{$this->pk};

不能使用普通变量语法访问类属性,它必须始终使用->::(取决于它们是按对象还是静态属性)。

PHP需要一个隐式$this->,而在Java中,用它的变量名访问类属性是可以的。

这意味着,${$this->pk}将等于仍然需要$this->$username,您应该使用:$this->{$this->pk}来实现您想要的。

但是,我强烈建议您更改类结构,这样您就不需要在运行时使用动态(公共)变量。

也许应该是这样。您的Table类中没有成员$username。在$Table的分配中有一个错误。

class Table
{
public $username;
...
}
$Table=new Table();
$pk='username'; //here I set what is PK column in my table
$Table->$pk='sbrbot'; //here I dynamically define variable and set $Table->username='sbrbot'

第二个问题:

 $value=${$this->pk}

这不起作用,因为您确实将其分配给了$This->用户名。