将配置文件中的数组作为 属性 返回到 class 脚本

Returning an array from configuration file to class script as a property

我有一个配置文件,我正在尝试从配置 class 访问它。配置文件将 mysql 数据作为数组:

<?php
  $config = array(
   'mysql' => array(
    'host' => 'localhost',
    'user' => 'test',
    'pass' => 'pass',
    'db' => 'test'
    )
  );
  return $config;

我希望能够使用类似 Config::get('mysql/host) 的方式访问此数组。这是 class 脚本:

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

我不确定如何使用需求文件中的 return 设置配置 属性。我得到一个错误,我是 "using $this not in an object context".
如何从 include/require 正确设置 class 变量?

额外问题:是否建议从单独的方法或在 class 构造函数中设置 $config 数组?

问题是您在静态上下文中引用 $this(实例引用)。要么去掉 "static" 关键字,要么也将 $config 声明为静态的,然后将其引用为 static::$config 而不是 $this->config.

您可以使用 spl_autoload_register 允许您初始化 class 而无需在每个 class.

中进行这些配置

这是我用来自动加载文件夹中所有 class 的内容

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_once("configuration.php"); 可以简单地调用

Config::get('mysql/host')
Config::get('mysql/dbname')
Config::get('mysql/username')
Config::get('mysql/password')