Answer the question
In order to leave comments, you need to log in
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;
$conf_host = 'localhost';
$conf_port = 3306;
$conf_user = 'root';
$conf_password = 'ПАРОЛЬ';
$conf_db = 'БАЗА';
$conf_authme_table = 'users';
Answer the question
In order to leave comments, you need to log in
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);
return [
'login'=>'myLogin',
'password'=>'myPassword',
'dbName'=>'myDbName'
];
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
}
}
$conf = include "/engine/data/dbconfig.php";
$config = new Config($conf);
$constroller = new AuthController($config);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question