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.

3
  • try posting relevant details of your code. Commented Jul 9, 2017 at 0:29
  • ok, added the comment! Commented Jul 9, 2017 at 0:36
  • what is the error you are facing? Commented Jul 9, 2017 at 0:40

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

I don't believe this is technically 'variable variables' ... anyway, stackoverflow.com/questions/251485/… shows several different methods.
thanks Alex Tartan and user2864740. Both your answers are very helpful. Learnt something new about PHP today. Have a great day ahead :))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.