PHP 和 PDO 类问题

PHP and PDO class question(PHP 和 PDO 类问题)
本文介绍了PHP 和 PDO 类问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我对 OOP 风格的 PHP 很陌生,我也在尝试实现 PDO.我在网上找到了这个处理数据库连接的不错的小类,但是我不知道如何从另一个类访问它.代码如下:

I am very new to OOP styled PHP, and I am trying to implement PDO as well. I found this nice little class online which handles the database connection, however I have no idea how to access it from another class. Here is the code:

  class PDO_DBConnect {
    static $db ;
    private $dbh ;
    private function PDO_DBConnect () {
        $db_type = 'mysql';  //ex) mysql, postgresql, oracle
        $db_name = 'postGal';
        $user = 'user' ;
        $password = 'pass' ;
        $host = 'localhost' ;
        try {
            $dsn = "$db_type:host=$host;dbname=$db_name";
            $this->dbh = new PDO ( $dsn, $user, $password);
            $this->dbh->setAttribute(PDO::ATTR_PERSISTENT, true);
            $this->dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        } catch ( PDOException $e ) {
            print "Error!: " . $e->getMessage () . "
" ;
            die () ;
        }
    }

    public static function getInstance (  ) {
        if (! isset ( PDO_DBConnect::$db )) {
            PDO_DBConnect::$db = new PDO_DBConnect ( ) ;
        }
        return PDO_DBConnect::$db->dbh;
    }
  }

  $db_handle = PDO_DBConnect::getInstance(); 

    class Person 
  {
    function __construct()
    {
      $STMT = $db_handle->prepare("SELECT title FROM posts WHERE id = ? AND author = ? LIMIT 20");
      $STMT->execute(array('24', 'Michael'));

      while ($result = $STMT->fetchObject()) 
      {
        echo $result->title;
        echo "<br />";
      }  
    }
  }

如何访问我的 Person 类中的 $db_handle 变量?我是否必须在 Person 类中实例化变量?如果是这样,那是否意味着我将始终必须将其称为 $this->db_handle ?我希望避免这种情况.(我对类的变量作用域仍然只有非常基本的了解)

How can I gain access to the $db_handle variable inside of my Person class? Do i have to instantiate the variable inside of the Person class? If so, does that mean I will always have to call it as $this->db_handle ? I was hoping to avoid that. (I still only have a very basic understanding of variable scope with classes)

推荐答案

有(至少)三种方法来处理这个问题.最便携且经常被推荐的方法称为依赖注入",您可以通过它的 __construct() 将数据库句柄传递到您的类中,并将其存储在类变量中.需要使用 $this->db 访问它,就像您不想做的那样.

There are (at least) three ways to handle this. The most portable, and oft recommended is called "dependency injection", whereby you pass the database handle into your class via its __construct() and store it in a class variable. Requires accessing it with $this->db like you didn't want to have to do.

class Person {
  // Member to hold the db handle
  public $db;

  public function __construct($db_handle) {
    // Assign the handle to a class member variable in the constructor
    $this->db = $db_handle;
  }
  public function otherFunc() {
    $this->db; // do something
  }
}

$person = new Person($db_handle);

下一个方法是在构造函数中实例化 $db_handle 而不是将其传入.这有点难以测试和调试.

Next method would be to instantiate the $db_handle inside the constructor rather than passing it in. This is a little harder to test and debug.

class Person {
   public $db;
   public function __construct() {
      $this->db = PDO_DBConnect::getInstance();
   }
}

最后,您可以在课堂中使用 $db_handle 作为 global 调用它.这可能是最难阅读和调试的.

Finally, you can call $db_handle as a global whenever you use it in your class. This is perhaps the hardest to read and debug.

class Person {
  public function __construct() {
    global $db_handle;
  }
  public function otherFunc() {
    global $db_handle;
    $db_handle; // do something
  }
}

这篇关于PHP 和 PDO 类问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

DeepL的翻译效果还是很强大的,如果我们要用php实现DeepL翻译调用,该怎么办呢?以下是代码示例,希望能够帮到需要的朋友。 在这里需要注意,这个DeepL的账户和api申请比较难,不支持中国大陆申请,需要拥有香港或者海外信用卡才行,没账号的话,目前某宝可以
PHP通过phpspreadsheet导入Excel日期,导入系统后,全部变为了4开头的几位数字,这是为什么呢?原因很简单,将Excel的时间设置问文本,我们就能看到该日期本来的数值,上图对应的数值为: 要怎么解决呢?进行数据转换就行,这里可以封装方法,或者用第三方的
mediatemple - can#39;t send email using codeigniter(mediatemple - 无法使用 codeigniter 发送电子邮件)
Laravel Gmail Configuration Error(Laravel Gmail 配置错误)
Problem with using PHPMailer for SMTP(将 PHPMailer 用于 SMTP 的问题)
Issue on how to setup SMTP using PHPMailer in GoDaddy server(关于如何在 GoDaddy 服务器中使用 PHPMailer 设置 SMTP 的问题)