Php 将数组作为属性从配置文件返回到类脚本
我有一个配置文件,我正试图从配置类访问它。配置文件将mysql数据作为一个数组:Php 将数组作为属性从配置文件返回到类脚本,php,class,oop,multidimensional-array,configuration-files,Php,Class,Oop,Multidimensional Array,Configuration Files,我有一个配置文件,我正试图从配置类访问它。配置文件将mysql数据作为一个数组: <?php $config = array( 'mysql' => array( 'host' => 'localhost', 'user' => 'test', 'pass' => 'pass', 'db' => 'test' ) ); return $config; 我不知道如何使用require文件的返回设置con
<?php
$config = array(
'mysql' => array(
'host' => 'localhost',
'user' => 'test',
'pass' => 'pass',
'db' => 'test'
)
);
return $config;
我不知道如何使用require文件的返回设置config属性。我得到一个错误,我正在使用$this而不是在对象上下文中。
如何从include/require正确设置类变量
附加问题:建议从单独的方法或在类构造函数中设置$config数组吗?问题是,您在静态上下文中将$this引用为实例引用。去掉static关键字,或者也声明$config static,然后将其引用为static::$config而不是$this->config。您可以使用它来初始化类,而不需要在每个类中使用这些配置 这是我用来自动加载文件夹中所有类的
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 ) {
}*/
}
}
}
}
这样您就可以调用而不是$this->config=require\u onceconfiguration.php;你只要打个电话就行了
Config::get('mysql/host')
Config::get('mysql/dbname')
Config::get('mysql/username')
Config::get('mysql/password')
我的印象是,在全局范围内包含此类信息不太安全,将其存储在非公共目录中的ini/配置文件中是最佳做法。
Config::get('mysql/host')
Config::get('mysql/dbname')
Config::get('mysql/username')
Config::get('mysql/password')