我有以下内容,但是我无法访问初始db类之外的数据库函数?
谢谢!
database.php中
class db
{
private $connection;
public function __construct()
{
$this->connection = new PDO();
}
}
admin.php的
class admin
{
private $connection
public function __construct(db $connection)
{
$this->connection = $connection;
}
function myFunc()
{
// How do I access the connection here?
}
}
main.php
//include db.php
//include admin.php
$connection = new db();
$admin = new admin($connection);
// How do I access the DB here?
答案 0 :(得分:1)
在您的管理类中,您将连接定义为类的私有属性。因此,在myFunc函数中,您只需执行$ this->连接即可访问您在构造函数中创建的连接。
在main.php文件中,初始化数据库对象的对象不是连接。它是整个db对象,因此您无法将连接本身传递给admin类(它被定义为private,因此类外的任何人都无法查看它)。但是,为什么需要将它传递给管理类?管理数据库连接应该是DB类的责任。
换句话说,您想通过将数据库连接暴露给管理类来实现什么?
Upate:根据回复,这是一个建议的答案:
class Database {
private $connection;
public function __construct() {
$this->connection = new PDO();
}
}
class Admin {
private $db;
public function __construct() {
$this->db = new Database();
}
public function myFunc() {
$this->db->query('...');
}
}
在你的main.php文件中:
$admin = new Admin();
$admin->myFunc();
请记住,每个管理对象都将创建一个与数据库的新连接,因此如果您创建了许多管理对象,则可能会遇到一些问题。您可以通过将DB声明为单身来解决这个问题。
答案 1 :(得分:1)
首先,为什么要将PDO
封装到包含该对象的类中?你不能直接使用PDO
吗?
其中一种常见做法是在db类中实现getter,例如:
class db {
...
public function getPDO(){
return $this->connection;
}
}
另一种方法是重新实现每个函数(为什么要这样做?!),或使用__call
魔术函数...
或者只是公开$connection
;)
或者您可以延长PDO
课程(我不确定它是否有用):
class DB extends PDO {
public function __construct ( $dsn, $username = null, $password = null, $driver_options = array()){
parent::__construct( $dsn, $username, $password, $driver_options);
... more of your stuff
}
public function myFunc(){
$this->...
}
}
答案 2 :(得分:1)
这个怎么样:更新了
<pre>
<?php
class DB {
private $host;
private $user;
private $pass;
private $dbase;
private $connection;
public function __construct($host,$user,$pass,$dbase)
{
$this->host = $host;
$this->user = $user;
$this->pass = $pass;
$this->dbase = $dbase;
$this->connection = new PDO("mysql:host=$this->host;dbname=$this->dbase", $this->user, $this->pass);
}
public function connect()
{
return $this->connection;
}
public function close()
{
unset($this->connection);
return true;
}
}
$dbh = new DB('localhost','root','','inventory');
$result = $dbh->connect()->query("SELECT * FROM products")->fetchAll(PDO::FETCH_ASSOC);
print_r($result);
?>
</pre>
答案 3 :(得分:0)
更新了文件分隔
<强> database.php中强>
class db
{
private $connection;
public function __construct()
{
$this->connection = new PDO();
}
}
<强> admin.php的强>
class admin
{
private $connection
public function __construct(db $connection)
{
$this->connection = $connection;
}
function myFunc()
{
return $this->connection->prepare('SQL');
}
function getConnection()
{
return $this->connection;
}
}
<强> main.php 强>
require_once 'database.php';
require_once 'admin.php';
$connection = new db();
$admin = new admin($connection);
$admin->myFunc()->execute();