gpt4 book ai didi

php - 如何使用从一个类到另一个类的连接

转载 作者:可可西里 更新时间:2023-11-01 07:58:05 25 4
gpt4 key购买 nike

class Database {

public $isConn;
private static $_instance = null;
private $datab;

// connect to db
public function __construct($username = "root", $password = "", $host = "localhost", $dbname = "market", $options = []) {
$this->isConn = TRUE;
try {
$this->datab = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
$this->datab->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->datab->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
} catch (PDOException $e) {
throw new Exception($e->getMessage());
}
}

public static function getInstance() {
if (!isset(self::$_instance)) {
self::$_instance = new Database();
}
return self::$_instance;
}

现在在每个需要数据库连接的类中

class test {

private $_db = null;

public function __construct() {
$this->_db = Database::getInstance();
}

public function test(){
return $this->_db->getRow("SELECT * FROM users", PDO::FETCH_ASSOC, []);
}

public static function testStatic(){
return $this->_db->getRow("SELECT * FROM users", PDO::FETCH_ASSOC, []);
}

现在它给我一个错误说不能使用 $this,那么我如何使用 self::来使用它?

现在如何在静态函数和非静态函数中一起使用它

最佳答案

在需要时获取数据库实例。

class test {

public function test(){
return Database::getInstance()->getRow("SELECT * FROM users", PDO::FETCH_ASSOC, []);
}

public static function testStatic(){
return Database::getInstance()->getRow("SELECT * FROM users", PDO::FETCH_ASSOC, []);
}
}

关于php - 如何使用从一个类到另一个类的连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42533817/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com