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.
You can use spl_autoload_register allows you to initialize the class without requiring those config in your every class.
This is what I used for auto-loading all class in my folder
define('__ROOT__', dirname(dirname(__FILE__)));
$GLOBALS['config'] = array(
'mysql' => array(
'host' => 'host',
'username' => 'root',
'password' => '',
'dbname' => 'dbname'
)
);
spl_autoload_register('autoload');
function autoload($class , $dir = null){
if(is_null($dir)){
$dir = __ROOT__.'/class/';
}
foreach ( array_diff(scandir($dir), array('.', '..')) as $file) {
if(is_dir($dir.$file)){
autoload($class, $dir.$file.'/');
}else{
if ( substr( $file, 0, 2 ) !== '._' && preg_match( "/.php$/i" , $file ) ) {
include $dir . $file;
// filename matches class?
/*if ( str_replace( '.php', '', $file ) == $class || str_replace( '.class.php', '', $file ) == $class ) {
}*/
}
}
}
}
So that you can call instead of $this->config = require_once("configuration.php");
can simply just call
Config::get('mysql/host')
Config::get('mysql/dbname')
Config::get('mysql/username')
Config::get('mysql/password')