【问题标题】:PHP - Using PDO connections across classesPHP - 跨类使用 PDO 连接
【发布时间】:2012-07-13 21:28:32
【问题描述】:

[编辑/更新]

请允许我解释一下情况。我有三个文件:

下面是 db.class.php。调用时,它在构造函数中连接到数据库,并在析构函数中关闭连接。如果您注意到 query() 方法,那么它现在只是一个静态 INSERT,因为这就是我卡住的地方。

<?php
//
// Class: db.class.php
// Desc: Connects to a database and runs PDO queries via MySQL
// Settings:
error_reporting(E_ALL);
////////////////////////////////////////////////////////////
class Db
{
    # Class properties
    private $DBH; // Database Handle
    private $STH; // Statement Handle

    # Func: __construct()
    # Desc: Connects to DB
    public function __construct()
    {
        // Connection information
        $host   = 'localhost';
        $dbname = 'removed';
        $user   = 'removed';
        $pass   = 'removed';

        // Attempt DB connection
        try
        {
            $this->DBH = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);
            $this->DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            echo 'Successfully connected to the database!';
        }
        catch(PDOException $e)
        {
            echo $e->getMessage();
        }
    }

    # Func: query(sql statement)
    # Desc: Sends a query to the DB
    public function query($sql_statement)
    {
        $sql = array(':color' => $sql_statement);
        $this->STH = $this->DBH->prepare("INSERT INTO color_table (color) value ( :color )");
        $this->STH->execute($sql);
    }

    # Func: __destruct()
    # Desc: Disconnects from the DB
    public function __destruct()
    {
        // Disconnect from DB
        $this->DBH = null;
        echo 'Successfully disconnected from the database!';
    }
}
?>

下面是colors.class.php。目前,它只有一个插入功能。我要做的基本上是从 db.class.php 中提取我在 query() 函数中的内容并将其放入 insertColor() 函数中,并传递整个 SQL 语句,无论它是插入、删除、或更新到 query() 函数。

<?php
//
// Class: colors.class.php
// Desc: Provides methods to create a query to insert,
//       update, or delete a color from the database.
////////////////////////////////////////////////////////////
class Colors
{
    # Class properties
    protected $db;

    # Func: __construct()
    # Desc: Passes the Db object so we can send queries
    public function __construct(Db $db)
    {
        $this->db = $db;
    }

    # Func: insertColor()
    # Desc: Sends an INSERT querystring
    public function insertColor($color)
    {
        $this->db->query($color);
        echo 'Inserted color:' . $color;
    }
}
?>

下面是colors.php,上面的所有内容都在其中被实例化和实现。所以在这里我将传递我真正想要插入数据库的颜色。

<?php
Require('db.class.php');
Require('colors.class.php');

$db = new Db;
$colors = new Colors($db);
$colors->insertColor('TestColor'); // Passing the color here to be put into an insert statement

?>

我基本上卡住的地方是我试图让 colors.class.php 创建一个 PDO 语句,然后在它们准备好运行时将其传递给 db.class.php query() 方法。现在,PDO 语句只是在 query() 方法中定义,但我试图避免这种情况。本质上,我想从 query() 方法中提取我所拥有的内容,并将其拆分为 Colors 类中的三个方法,一个用于插入、更新和删除。

但是,我对 OOP 编程还很陌生,并且在所有语法方面都遇到了问题,我也不知道这是否是一个好方法。非常感谢任何帮助,如果需要更多详细信息或信息,请告诉我。

【问题讨论】:

  • 不需要(),像所有函数和变量一样,区分大小写?
  • @ReyGonzales Functions are not case sensitive,尽管变量是。 require 实际上不是一个函数,它是一种语言结构——而且这些也是不区分大小写的。
  • ftr、require* 或 include* 不是函数,而是语句。所以应该写成require 'db.class.php';
  • @ReyGonzales PHP 不区分大小写!
  • @Besnik 变量名区分大小写,(默认情况下)常量名也是如此。

标签: php oop pdo


【解决方案1】:

是的,因为$db 是方法内部的局部变量。将其作为参数传递:

class Colors
{
  protected $db;

  public function __construct(Db $db = null)
  {
    $this->db = $db;
  }

  public function insertColor()
  {
    if ($this->db != null)
    {
      $this->db->query();
    }
  }
}

query是一种方法,所以你必须加上括号:$db-&gt;query()

【讨论】:

  • 推荐 global 作为 OP 标记为 OOP 的解决方案不是一个好主意。
  • @MikePurcell 你是对的!我删除了第一种方法。只是又快又脏……
  • 更近,但没有雪茄。我用我遇到的问题更新了我的帖子。感谢大家迄今为止的帮助!
  • @Xenostar 您必须将数据库实例传递给新的颜色对象:$colors = new Colors($db);
  • 看来您已将 $db 设置为 __construct 参数,该参数为 null,因为您在构造对象时实际上并没有传递它。
【解决方案2】:

我将从您的类文件中删除数据库的包含和初始化,并将其放入colors.php 本身。然后将$db 作为参数传递给构造函数:

<?php
Require('db.class.php');
Require('colors.class.php');

$db = new Db;

$colors = new Colors($db);
$colors->insertColor();
?>

我还将删除构造函数中的默认值,因为如果没有数据库,Colors 类将无法工作:

public function __construct(Db $db)    // constructor Colors class

最后,我会查看 autoloading 的类,这样您就不必手动要求它们了。

【讨论】:

    【解决方案3】:

    $db-&gt;query; 更改为$db-&gt;query();

    另外,需要将 $db 声明为全局变量才能像这样访问它。可能要考虑将其设为Colors 的私​​有财产

    【讨论】:

    • @Besnik 已修复。感谢您借用我的其余答案并对我投反对票,这样您就可以获得一些额外的积分
    猜你喜欢
    • 1970-01-01
    • 2012-07-15
    • 1970-01-01
    • 2015-08-04
    • 1970-01-01
    • 2013-05-13
    • 1970-01-01
    • 2013-03-27
    • 2014-02-02
    相关资源
    最近更新 更多