Hello, I am just wondering if this is something I can do in php. I have a class called settings. In it have variables such as sitetitle, adminemail, etc. When I retrieve my settings from the database I want to populate my settings object. The way my settings looks like: name value datatype sitetitle FunnyCats.com string adminemail string Is there way a to dynamically cooraliate the object property with the value in the name field from the database. For example if the setting is sitetitle then I want the value assigned to $settings->sitetitle? I'm not sure if I explained it clearly or not. Thanks in advance.
I'm not too clear about your post but here's an example. <?php class SETTING{ public $sitetitle = ''; public $adminemail = ''; public function display(){ echo 'Title : '.$this->sitetitle.'<br> Admin email : '.$this->adminemail; }//end display function }//end SETTING class $conn = mysql_connect('server','username','password'); mysql_select_db('dbname',$conn); $query = 'SELECT sitetitle,adminemail FROM yourtablename'; $result = mysql_query($query,$conn); $setting = new SETTING; list($setting->sitetitle,$setting->adminemail) = mysql_fetch_array($result); $setting->display(); ?> PHP:
That's close. I was hoping for something where I wouldn't need to hard code it. For example of how it should look like. $query = "SELECT * FROM t_settingssite"; while($row = mysql_fetch_array($result)) { $settings->$row["name"] = $row["value"]; } Code (markup): $row["name"] will have the name of the variable. ex. $settings->sitetitle. $row["value"] will have the value. ex. "My web site title".
It looks like you already have a valid solution but another way is with a getter: class settings { // Associative array of option names and their values private $settings; // Constructor fetches settings from database public function __construct() { // Grab data and store it in $this->settings, e.g. while ( $row = mysql_fetch_array($result) ) { $this->settings[$row['name']] = $row['value']; } } // Getter public function __get($name) { // Check setting exists and return the appropriate value if ( isset($this->settings[$name]) ) { return $this->settings[$name]; } // No value for this setting, return a default return NULL; } } PHP: