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

时间:2018-01-12 10:34:33

标签: php mysql class private

我正在使用config.php文件来表示类似的东西,我试图将我的mysql凭据放在那里然后在不同的文件中使用它们,但它没有传递值,

是否有任何可以帮助我找到解决方案。

code 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 dbconnection:

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

提前致谢=)

3 个答案:

答案 0 :(得分:2)

不要将其视为传递变量,而应将其视为传递配置。您的Database类必须知道这些配置选项才能使用它。换句话说:一旦你创建了一个类Database的实例,它应该被配置并准备好使用,就像任何服务一样。 我强烈建议您遵循injecting the configuration as a dependency的规则。

答案 1 :(得分:1)

在您的课程中加入'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
        {

答案 2 :(得分:0)

您可以尝试以下代码:

<强>的config.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']);
        //...
    }
    //...
}

<强> dbconnect.php

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