Kereell
Kereell

Reputation: 69

Dynamically access object property by using "$this"

I have next lines in my code to get the entity in ZF3:

$entity = $this->userCredentialsTableGateway
               ->getResultSetPrototype()
               ->getArrayObjectPrototype();

To automate it for different tables I created a function:

private function getEntityFromGateway( $table )
{
    $context = $table . "TableGateway";
    return $this->$context
                ->getResultSetPrototype()
                ->getArrayObjectPrototype();
}

When I try to get

$entity = $this->getEntityFromTableGateway( "UserCredentials" )

it gives an error:

Undefined property: 
User\DataGateway\UserDataGateway::$UserCredentialsTableGateway

So, some why $this->$var acts like $this->$$var. PHP version 7.2

Upvotes: 1

Views: 66

Answers (1)

A l w a y s S u n n y
A l w a y s S u n n y

Reputation: 38502

I think you need to do slight modification on your existing code.

  1. Wrap variable and string with curly braces like this "{$table}TableGateway"
  2. Lower case table name's first character only e.g if you've all table at first later small case use instead it like this $context = lcfirst("{$table}TableGateway")

So your code will be like this

private function getEntityFromGateway( $table )
{
    $context = lcfirst("{$table}TableGateway");
    return $this->$context
                ->getResultSetPrototype()
                ->getArrayObjectPrototype();
}

and call it like this way as you're already doing,

$entity = $this->getEntityFromTableGateway( "UserCredentials" )

Upvotes: 1

Related Questions