如何构造我的config.php文件以在其他文件的类中使用

如何构造我的config.php文件以在其他文件的类中使用,php,configuration-files,Php,Configuration Files,我在一个配置文件中有一些变量和常量,我想在另一个类的方法中使用它们,config.php和myclass.php都在同一个文件夹中 config.php <?php $a=1; 有更好的方法吗?您可以在配置文件中创建另一个类,它将作为所有配置值和操作的包装器。如果您在项目开发中重视OOP,这也是最好的方法 config.php class MyClass { protected function a () { include_once('config.php'); ec

我在一个配置文件中有一些变量和常量,我想在另一个类的方法中使用它们,
config.php
myclass.php
都在同一个文件夹中

config.php

<?php
$a=1; 

有更好的方法吗?

您可以在配置文件中创建另一个类,它将作为所有配置值和操作的包装器。如果您在项目开发中重视OOP,这也是最好的方法

config.php

class MyClass
{
  protected function a () {
   include_once('config.php');
   echo $a; //$a is undefined here 
  }
}
<?php
/**
 * PhpDoc...
 */
class YourConfig
{
  /**
   * Your constant value
   */
  const DB_HOST = 'localhost';

  /**
   * @var string Some description
   */
  private $layout = 'fluid';

  /**
   * Your method description
   * @return string layout property value
   */
  public function getLayout()
  {
    return $this->layout;
  }
}
<?php
/**
 * PhpDoc
 */
class MyClass
{
  private $config;

  public function __construct()
  {
    require_once( __DIR__ . '/config.php' );
    $this->config = new Config();
  }

  protected function a()
  {
    // get a config
    echo $this->config->getLayout();
  }
}

您可以根据需要使用和扩展此方法。

您还可以从包含的文件中返回变量(可能是数组?)。参见手册中关于
include
的示例#5看起来非常干净。谢谢