PHP将值从PHP文件传递到其他类
我正在使用一个config.php文件来模拟一些东西,我试图将我的mysql凭据放在那里,然后在另一个文件中使用它们,但它不会传递值 有什么能帮我找到解决办法的吗 代码config.php:PHP将值从PHP文件传递到其他类,php,mysql,class,private,Php,Mysql,Class,Private,我正在使用一个config.php文件来模拟一些东西,我试图将我的mysql凭据放在那里,然后在另一个文件中使用它们,但它不会传递值 有什么能帮我找到解决办法的吗 代码config.php: /* Database credentials*/ $dbHost = 'localhost'; $dbName = 'xx'; $dbUsername = 'xx'; $dbWachtwoord = 'xx'; 代码dbconnect.php: <?php include '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;
}
提前感谢=与其将其视为传递变量,不如将其视为传递配置。您的数据库类必须知道这些配置选项,才能使用它。换句话说:一旦创建了类数据库的实例,就应该像任何服务一样对其进行配置并准备好使用。
我强烈建议您遵循规则。在类中包含'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
{
您可以尝试以下代码: config.php dbconnect.php
变量范围:向我们展示如何调用dbConnection方法。然后有人可以帮你。$this->host=$GLOBALS['dbHost'];
<?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']);
//...
}
//...
}
public function dbConnection($dbHost, $dbName, $dbWachtwoord, $dbName)
{
//....
}