I have a class for configuration on my script and I implement the config. I then want to use the options as an object reference like the following, but not sure how to get it all the way to the final object field and also how to make it recognize sub arrays too
class Configuration {
public $cookies = array(
"cookie_prefix" => "site_",
"site_settings" => array(
"domain" => "somesite.com",
"https_only" => TRUE
),
"another_item" => "and some data too"
);
}
$config = new Configuration();
echo $config->cookies->cookie_prefix;
echo $config->cookies->site_settings->domain;
Right now it works if I do the following
echo $config->cookies['cookie_prefix'];
echo $config->cookies['site_settings']['domain'];
But I want it to be an object all the way down. Can't wrap my brain around this one for some reason?
I know this is easily done - I am just missing the way how...
My Answer:
public $general = array(
'site_name' => 'My Website',
'site_url' => 'http://www.example.com'
);
public $database = array(
'host' => 'localhost',
'username' => 'root',
'password' => 'password',
'database' => 'my_database'
);
}
$config = new Configuration();
// Accessing the general options
echo $config->general['site_name']; // Output: My Website
// Accessing the database options
echo $config->database['host']; // Output: localhost
// To access sub arrays, you can do something like this
$subArray = $config->database;
echo $subArray['host']; // Output: localhost
// Or directly
echo $config->database['host']; // Output: localhost
Rate this post
4 of 5 based on 9940 votesComments