PHP and PDO class question

后端 未结 3 1126
粉色の甜心
粉色の甜心 2020-12-18 06:53

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 ide

相关标签:
3条回答
  • 2020-12-18 07:16

    You should use Dependency Injection:

    $steve = new Person($db_handle);
    

    And yes, using the syntax you're hoping to avoid is the way to do it. You can always assign the class variable to a local method one by saying $dbh = $this->db_handle; which I believe is marginally faster.

    0 讨论(0)
  • 2020-12-18 07:18

    If you really must do database work from inside your Person object (separation of concerns says that this should be taken care of elsewhere), you can either pass it as a constructor argument (based on your usage, it looks like that may be the way you want to go), or as a setter injection. For the former:

    class Person
    {
        function __construct($db_handle)
        {
            // ... your existing code
    

    Then you instantiate your person object like so:

    $person = new Person($db_handle);
    

    That's really the only way you can avoid needing to use $this->db_handler without copying the variable into local scope.

    0 讨论(0)
  • 2020-12-18 07:33

    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);
    

    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();
       }
    }
    

    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
      }
    }
    
    0 讨论(0)
提交回复
热议问题