1

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

Kereell
  • 69
  • 7

1 Answers1

1

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" )
A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103
  • OMG! I can't believe that I've just misspelled the variable name! You are right - the first letter must be "lowercased". I didn't use PHP for some time so I decided that there are must be some rules with "$this" that I've forgot.. but it was silly misspelling.. Thanks for the answer! – Kereell Aug 24 '18 at 16:56
  • @kereell, glad it helps you somehow. Best of luck :) – A l w a y s S u n n y Aug 24 '18 at 16:57