I have a configuration file and I am trying to access it from a configuration class. The config file has the mysql data as an array:
<?php
$config = array(
'mysql' => array(
'host' => 'localhost',
'user' => 'test',
'pass' => 'pass',
'db' => 'test'
)
);
return $config;
I want to be able to access this array using something like Config::get('mysql/host). Here is the class script:
class Config {
public $config = null;
public static function get($path = null) {
$this->config = require_once("configuration.php");
print_r($this->config);
if($path) {
$path = explode('/', $path);
foreach($path as $bit) {
if(isset($config[$bit])) {
$config = $config[$bit];
} //End isset
} //End foreach
return $_config;
} //End if path
} //End method
} //End class
I'm not sure how to set the config property using the return from an require file. I am getting an error that I am "using $this not in an object context".
How is one to correctly set a class variable from an include/require?
Bonus question: Would it be recommended to set the $config array from a separate method or in the class constructor?
The problem is you're referring to $this (an instance reference) in a static context. Either get rid of the "static" keyword, or declare $config static as well, and then refer to it as static::$config instead of $this->config.