-1

I have a model called Treatment in CodeIgniter. I want to load and use this model 'dynamically'. That is, I don't want to have to call it directly by name (I am trying to generalize some code to use whatever model I tell it).

So, I do this:

$namespace = 'blah';
$modelName = 'Treatment';
...
$this->load->model($namespace . '/' . $modelName);
$this->model = $this->$$modelName;

However, I get an error when accessing the $this->$$modelName variable, saying that the variable 'Treatment' is undefined:

Undefined variable: Treatment ... Fatal error:  Cannot access empty
property in /mydir/application/controllers/rest/base_rest.php on line
202.

Where line 202 is the line where I am using the $this->$$modelName variable.

Now, if I changed line 202 to be:

$this->model = $this->Treatment;

It works fine.

Does anyone know why I can't seem to use the PHP $$ syntax here?

Jarrett
  • 1,767
  • 25
  • 47
  • Regular: `$this->Treatment`. Variable: `$this->$modelName` ???: `$this->$$modelName` – deceze Jul 25 '14 at 18:45
  • 1
    `$$` is the [Variable Variable](http://php.net/manual/en/language.variables.variable.php) syntax in `PHP`. I didn't know there was a different style of that syntax when referencing a Variable Variable in the way I am here (Although, now looking over it, the documentation has this in Example 1 :S). – Jarrett Jul 25 '14 at 18:48
  • Well, yes, it's looking for the variable variable called `$Treatment` to then use its value as object property name. – deceze Jul 25 '14 at 18:51

1 Answers1

1

You can't because it's not a supported syntax. Try

$this->{$modelName}

instead. e.g.

php > class foo { public $bar = 42; }
php > $x = new foo();
php > $y = 'bar';
php > echo $x->$$y;
PHP Notice:  Undefined variable: bar in php shell code on line 1
PHP Fatal error:  Cannot access empty property in php shell code on line 1
php > echo $x->{$y};
42php >
Marc B
  • 356,200
  • 43
  • 426
  • 500
  • Worked perfectly! Thanks @Marc! I'll accept your answer once SO lets me (~10 minutes from now). – Jarrett Jul 25 '14 at 18:46