zgr024
zgr024

Reputation: 1173

Calling a class in a namespace by variable in PHP

I have a function that displays a table based on a set of records given the id of the records only. The function then calls the class by variable pulled from an array of parameters. This worked just fine...

function displayTable($arr) {
...
    foreach ($a['ids'] as $key => $arr) 
    {
        $m=$a['model'];
        $o = new $m($arr['id']);
    ...
    }
}

The issue is I now have the class in a namespace and the following does not work and throws an error...

function displayTable($arr) {
...
    foreach ($a['ids'] as $key => $arr) 
    {
        $m=$a['model'];
        $o = new \My\New\Namespace\$m($arr['id']);
    ...
    }
}

Parse error: syntax error, unexpected '$m' (T_VARIABLE), expecting identifier (T_STRING)

How can I accomplish this?

Upvotes: 1

Views: 140

Answers (1)

dev-null-dweller
dev-null-dweller

Reputation: 29492

Just prepend namespace to variable, before object initialization:

$m = '\\My\\New\\Namespace\\' . $m;

Upvotes: 1

Related Questions