0

I have a field database record row that reads like this:

| id |  command  |
------------------
|  1 | getName() |

I also have a PHP entity that is User, and has the getName() function.

Assuming the database record is read and parsed into $record and I have $user, how do I concatenate $record with the $user command?

I tried $user-> . $record['command'] but obviously does not work. I want to avoid hardcoding as I need it to be dynamic if possible.

Example of code:

$record = DB::queryFirstRow("SELECT * from command_records WHERE id='1'");
$user = new User("Kenny");
// Here is where I'm trying to perform the $user->getName() 
// by reading $record['command']. $record['command'] is getName()
$user-> . $record['command']; 

It of course fails. I'm thinking of eval from googling earlier but can't get it to work out too.

Alex Tartan
  • 6,736
  • 10
  • 34
  • 45
Kenneal
  • 25
  • 4

1 Answers1

2

what you're looking for is PHP's variable variables

You can try something like:

class User
{
    public function getName()
    {
        return "SomeName";
    }
}

// assuming this is how your result looks like
$result = [
    'command' => 'getName()',
    // more data
];

$command = $result['command'];            // is "getName()"
$command = str_replace('()','',$command); // is "getName"
// you need to remove the '()'. just get the name of the method

$user = new User();
echo $user->{$command}();
// output: SomeName

See it here: https://3v4l.org/OVYAa

Alex Tartan
  • 6,736
  • 10
  • 34
  • 45
  • 1
    I don't believe this is technically 'variable variables' ... anyway, https://stackoverflow.com/questions/251485/dynamic-class-method-invocation-in-php shows several different methods. – user2864740 Jul 09 '17 at 00:54
  • thanks Alex Tartan and user2864740. Both your answers are very helpful. Learnt something new about PHP today. Have a great day ahead :)) – Kenneal Jul 10 '17 at 23:49