A
A
AndRussia2021-07-22 13:47:43
PHP
AndRussia, 2021-07-22 13:47:43

How to put variables from an include file into a class?

Good day. How to put variables through include from a file into a class?
Here is the code of the file I am including into:

require "/engine/data/dbconfig.php";

abstract class AuthMeController {
    const HOST = $conf_host;
    const USERNAME = $conf_user;
    const PASSWORD = $conf_password;
    const DATABASE = $conf_db;
    const AUTHME_TABLE = $conf_authme_table;

Here is the code for the file with the variables themselves:
$conf_host = 'localhost';
  $conf_port = 3306;
  $conf_user = 'root';
  $conf_password = 'ПАРОЛЬ';
  $conf_db = 'БАЗА';
  $conf_authme_table = 'users';

It returns:
Parse error: syntax error, unexpected '$conf_host' (T_VARIABLE) in W:\domains\fusion\authme\AuthMeController.php on line 10

Answer the question

In order to leave comments, you need to log in

3 answer(s)
K
Konstantin, 2021-07-22
@AndRussia

this is not the right approach from the start. no need to do "default configuration" through global variables.

class DbConnection
{
    private string $userName;
    private string $password;
    private string $dbname;

    public function __construct(string $userName, string $password, string $dbName)
    {
        $this->userName = $userName;
        $this->password = $password;
        $this->dbname = $dbName;
    }
}


class AuthController
{
    private DbConnection $dbConnection;

    public function __construct(DbConnection $connection)
    {
        $this->dbConnection = $connection;
    }
}

$dbSettings = include('dbconfig.php');
$connection = new DbConnection($dbSettings['login'], $dbSettings['password'], $dbSettings['dbName'] );
$controller = new AuthController($connection);

and in the dbconfig.php file
return [
'login'=>'myLogin',
'password'=>'myPassword',
'dbName'=>'myDbName'
];

S
Sergey delphinpro, 2021-07-22
@delphinpro

dbconfig.php

return [
  'host' => 'localhost';
  'port' => 3306;
  'user' => 'root';
  'password' => 'ПАРОЛЬ';
  'db' => 'БАЗА';
  'authme_table' => 'users';
];

class Config {
  public $host;
  public $user;
  // ...

  public function __construct(array $conf){
    $this->host = $conf['host'];
    $this->user = $conf['user'];
    // ...
  }
}

class AuthController {
  protected $config;

  public function __construct(Config $config){
    $this->config = $config
  }
}

Then
$conf = include "/engine/data/dbconfig.php";
$config = new Config($conf);
$constroller = new AuthController($config);

E
Eugene, 2021-07-22
@Nc_Soft

You invent dotenv

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question