【问题标题】:Using a config file from within a php class在 php 类中使用配置文件
【发布时间】:2013-02-02 07:40:42
【问题描述】:

我是 PHP OOP 的新手,但我对 OO 背后的概念有相当不错的理解。我想要一个配置文件,其中包含可在整个应用程序中使用的通用应用程序数据。很正常,但我不完全确定如何做到这一点。我不想创建一个类,然后在每个类中都需要该类、扩展它和/或需要配置文件。我的配置文件如下所示:

<?php

$configs = array(
   'pagination' => 20,
   'siteTitle' => 'Test site',
   'description' => 'This is a test description',
   'debug' => true
);

?>

我能想到的唯一事情是:

<?php 

class user {
   public function __construct() {
       require 'config.php';
       if(configs['debug']) {
           echo 'Debugging mode';
       }
   }
}

?>

我看到这种方法的问题是我必须在我想使用的每个类中手动包含这个配置文件,这似乎是多余的。理想情况下,我希望将文件包含在绝对根路径中,然后能够使用任何类中的任何值,但是如果您只需要类之外的文件,则该类将无法访问这些值。我也不想创建一个配置类,然后每个需要这些值的类都让它们扩展配置类。再一次,这似乎是多余的。

不确定我是否说得通,我只是想要一种简单的方法来在每个类中携带配置值并使用它们,而不必输入过多的冗余代码。

提前致谢!

【问题讨论】:

标签: php file class config


【解决方案1】:

在一个类 (config.php) 中声明一个变量,然后在另一个类中使用它是不好的做法。您应该从配置文件中返回配置数组,然后您可以将其分配给变量,或者根据需要将其作为参数传递。

试试这样的:

config.php:

<?php
return array( /* ... config values ... */ );

user.php:

<?php
class User { 
    private $config;

    public function __construct(array $config) {
        $this->config = $config;
        if ($this->config['debug']) {
            // debug
        }
    }

    public function someOtherMethod() {
        if ($this->config['debug']) {
            // debug
        }
    }
}

调用代码:

<?php
$user = new User(require 'config.php');
$user->someOtherMethod();

【讨论】:

  • 我最终查看了 Wordpresses 方法,他们使用 PHP 定义,我更喜欢它,感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-04-12
  • 2012-05-09
  • 2013-01-23
  • 2013-05-13
  • 2012-10-28
  • 2021-09-02
  • 1970-01-01
相关资源
最近更新 更多