sbrbot
sbrbot

Reputation: 6447

Access property whose name is in another property

I have a class which dynamically wraps all my database tables:

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'

The question is when I want to retrieve this value from class I must to it in two steps;

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

why this:

$value=${$this->pk}

does not work?

Upvotes: 0

Views: 67

Answers (3)

Dave Chen
Dave Chen

Reputation: 10975

PHP requires an implicit $this->, whereas in Java it would be fine to access a class property with its variable name.

This means, ${$this->pk} would be equal to $username which still requires $this->, you should use: $this->{$this->pk} to achieve what you what.

I would highly recommend however, changing your class structure so you don't need to have dynamic (public) variables at runtime.

Upvotes: 1

Barmar
Barmar

Reputation: 780842

It should be:

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

You can't access class properties using normal variable syntax, it always has to be with -> or :: (depending on whether they're per-object or static properties).

Upvotes: 2

Franz Holzinger
Franz Holzinger

Reputation: 998

Maybe it should be this. You did not have the member $username in your Table class. And there is a bug in your assignement to $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'

second question:

 $value=${$this->pk}

This does not work, because you did assign it to $this->username.

Upvotes: -1

Related Questions