Reputation: 33196
Is it possible to include a file with PHP variables inside a class? And what would be the best way so I can access the data inside the whole class?
I have been googling this for a while, but none of the examples worked.
Upvotes: 14
Views: 29091
Reputation: 4361
From a performance point of view, it would be better if you will use a .ini file to store your settings.
[db]
dns = 'mysql:host=localhost.....'
user = 'username'
password = 'password'
[my-other-settings]
key1 = value1
key2 = 'some other value'
And then in your class you can do something like this:
class myClass {
private static $_settings = false;
// This function will return a setting's value if setting exists,
// otherwise default value also this function will load your
// configuration file only once, when you try to get first value.
public static function get($section, $key, $default = null) {
if (self::$_settings === false) {
self::$_settings = parse_ini_file('myconfig.ini', true);
}
foreach (self::$_settings[$group] as $_key => $_value) {
if ($_key == $Key)
return $_value;
}
return $default;
}
public function foo() {
$dns = self::get('db', 'dns'); // Returns DNS setting from db
// section of your configuration file
}
}
Upvotes: 1
Reputation: 2493
Actually, you should append data to the variable.
<?php
/*
file.php
$hello = array(
'world'
)
*/
class SomeClass {
var bla = array();
function getData() {
include('file.php');
$this->bla = $hello;
}
function bye() {
echo $this->bla[0]; // Will print 'world'
}
}
?>
Upvotes: 2
Reputation: 39704
The best way is to load them, not to include them via an external file.
For example:
// config.php
$variableSet = array();
$variableSet['setting'] = 'value';
$variableSet['setting2'] = 'value2';
// Load config.php ...
include('config.php');
$myClass = new PHPClass($variableSet);
// In a class you can make a constructor
function __construct($variables){ // <- As this is autoloading, see http://php.net/__construct
$this->vars = $variables;
}
// And you can access them in the class via $this->vars array
Upvotes: 14