Search code examples
phpcodeignitervariable-variables

CodeIgniter access model with $$ fails


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?


Solution

  • 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 >