Dynamic MySQL table name within a class

233 views Asked by At
class Patient {

   protected static $table_name = "siteA";
   public $id;
   public $first_dx;
   public $confidence;
   public $second_dx;
   public $path_dx;

}

I have simply shown the class attributes here. I have CRUD methods within the class but I haven't posted them simply to make this clear. The $table_name above in this case is siteA however I need to make this dynamic. When a user logins into my site their site is saved in the session (siteA, siteB, siteC etc) and I need the table name here to switch depending on the person logged in. The site is $_SESSION['user_site'], and I have tried to use this in curly braces, no quotes, quotes etc etc and no luck.

Clearly there is knowledge I am lacking. Can this be done?

1

There are 1 answers

3
php_nub_qq On BEST ANSWER
class Patient {

    protected static $table_name = "siteA";
    public $id;
    public $first_dx;
    public $confidence;
    public $second_dx;
    public $path_dx;

    public function __construct(){
        self::$table_name = $_SESSION['user_site'];
    }

}

Basically a constructor is a magic method that will be the first thing to execute when creating a new instance of your object, which is a perfect candidate for initializing values.

The reason you cannot use $_SESSION['user_site'] in the declaration of the properties is because they are being created at compile time where the session doesn't yet exist.