php将值从php文件传递到其他类

at0kjp5o  于 2021-06-25  发布在  Mysql
关注(0)|答案(3)|浏览(375)

我正在使用一个config.php文件来模拟一些东西,我试图把我的mysql凭据放在那里,然后在另一个文件中使用它们,但是它没有传递值,
有什么能帮我找到解决办法吗。
代码config.php:

/* Database credentials*/
$dbHost = 'localhost';
$dbName = 'xx';
$dbUsername = 'xx';
$dbWachtwoord = 'xx';

代码dbconnect.php:

<?php include 'config.php';
class Database
{
    private $host;
    private $db_name;
    private $username;
    private $password;
    public $conn;

    public function dbConnection()
    {
        $this->host = $dbHost;
        $this->db_name = $dbName;
        $this->username = $dbUsername;
        $this->password = $dbWachtwoord;
        $this->conn = null;
        try
        {
            $this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
            $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        }
        catch(PDOException $exception)
        {
            echo "Connection error: " . $exception->getMessage();
        }

        return $this->conn;
    }
}

class.user数据库连接:

<?php
require_once('config.php');
require_once('dbconnect.php');

class USER
{   

    private $conn;

    public function __construct()
    {
        $database = new Database();
        $db = $database->dbConnection();
        $this->conn = $db;
    }

    public function runQuery($sql)
    {
        $stmt = $this->conn->prepare($sql);
        return $stmt;
    }

提前感谢=)

kgsdhlau

kgsdhlau1#

您可以尝试以下代码:
配置.php

<?php 
return [
    'dbHost' => 'localhost',
    'dbName' => 'xx',
    'dbUsername' => 'xx',
    'dbWachtwoord' => 'xx',
];

用户类

class USER
{   

    private $conn;
    private $config;

    public function __construct()
    {
        $this->config = include "config.php";
        $database = new Database(this->config['dbHost'], $this->config['dbUsername'], $this->config['dbWachtwoord'], $this->config['dbName']);
        //...
    }
    //...
}

数据库连接.php

public function dbConnection($dbHost, $dbName, $dbWachtwoord, $dbName)
{
    //....
}
x6492ojm

x6492ojm2#

与其将其视为传递变量,不如将其视为传递配置。数据库类必须知道这些配置选项才能使用。换句话说:一旦你创建了一个类数据库示例,它就应该被配置好并且可以使用,就像任何服务一样。我强烈建议您遵循将配置作为依赖项注入的规则。

ymdaylpp

ymdaylpp3#

在类中包含'config.php'

public function dbConnection()
    {
        include 'config.php';
        $this->host = $dbHost;
        $this->db_name = $dbName;
        $this->username = $dbUsername;
        $this->password = $dbWachtwoord;
        $this->conn = null;
        try
        {

相关问题