3

I'm attempting to learn codeigniter for php and I've come across this block of code where it seems the instructor is trying to change a constant variable. First I'm clueless as to why the curly braces are used and then I'm curious as to exactly what is going on with that constant variable.

<?php
    class MY_Model extends CI_Model {
        const DB_TABLE = 'abstract';
        const DB_TABLE_PK = 'abstract';

        private function insert() {
            $this->db->insert($this::DB_TABLE, $this);
            $this->{$this::DB_TABLE_PK} = $this->db->insert_id();
        }
    }
?>

Can someone please explain not only the use of curly braces here, but also how it's possible to assign a new value to the defined constant?

Highspeed
  • 442
  • 3
  • 18
  • 1
    These answers may help: http://stackoverflow.com/a/9056123/1438393 , http://stackoverflow.com/questions/1147937/ – Amal Murali Oct 01 '13 at 21:45

1 Answers1

1

They're not assigning to a constant. They're using the constant as a lookup key, to create a "dynamic" attribute of the object.

This line:

$this->{$this::DB_TABLE_PK} = $this->db->insert_id();

boils down to

$this->{'abstract'} = $this->db->insert_id();

which is a perfectly acceptable construct. It's just creating an object attribute on-the-fly.

Marc B
  • 356,200
  • 43
  • 426
  • 500