0
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?

halfer
  • 19,824
  • 17
  • 99
  • 186
GhostRider
  • 2,109
  • 7
  • 35
  • 53

1 Answers1

0
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.

php_nub_qq
  • 15,199
  • 21
  • 74
  • 144
  • That works beautifully. May I ask, for my own knowledge....you left the table name as siteA in the declaration of the attributes. This presumably is a default and then when someone logs in, it gets overwritten, correct? So at compile time, the patient class gets created, and then the overwriting takes place at login?Forgive my ignorance...I am a Doctor who has been learning php for 4 months to create platform for collecting data from multiple hospitals (research). – GhostRider Dec 28 '13 at 12:50
  • the reason I ask is because if I replace siteA with " ", then it doesn't work. I thought " " could be used as a default. – GhostRider Dec 28 '13 at 12:57
  • @GhostRider with this setup `$table_name` will **always** be overwritten with whatever your session holds. So it doesn't matter what it is initially set to, it will be overwritten anyways. In this case it is best to not have any default value in order to save a little compile time but it is kind of an insignificant change. I have just copied your code and didn't make any changes to the properties, I did not explicitly leave it as 'siteA'. Hope that helps! – php_nub_qq Dec 28 '13 at 13:24