user2650277
user2650277

Reputation: 6739

How to structure my config.php file to use within classes in other files

I have some variables and constants in a config file that I want to use in a method of a class in another both config.php and myclass.phpare in the same folder.

config.php

<?php
$a=1; 

myclass.php

class MyClass
{
  protected function a () {
   include_once('config.php');
   echo $a; //$a is undefined here 
  }
}

Is there a better approach for this?

Upvotes: 2

Views: 1048

Answers (1)

MNR
MNR

Reputation: 757

You can create another class in your config file and it will serve as a wrapper for all your config values and operations. This is the best approach also if you are giving value to OOP in your project development.

config.php

<?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;
  }
}

myclass.php

<?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();
  }
}

You can use and extend this approach for what/however you want.

Upvotes: 1

Related Questions