Using a global DB variable inside classes in PHP

How to use global DB variable inside a class? Say I have this in my config.php

$dbh = new PDO("mysql:host=localhost;dbname=mydb", "root", "");

and I want to use this inner class $ dbh as follows (MyClass.php)

class MyClass
{
   public function DoSomething($plogin_id)
   {
        $sql = "SELECT * FROM mytable WHERE login_id = :login_id";      
        $stmt = $dbh->prepare($sql);    //line 14
        $stmt->bindParam(':login_id', $plogin_id, PDO::PARAM_STR);
   }
}

And inside my index.php file, I use this MyClass as follows:

include "config.php";
$MyObject = new MyClass();
$login_result = $MyObject->DoSomething("admin");

This gives me an error:

Fatal error: call a member function Prepare () for a non-object in C: \ XAMPP \ HTDOCS \ MyProject \ admin \ includes \ classes \ MyClass.php on line 14

+3
source share
3 answers

- $dbh MyClass. , MyClass.

MyClass index.php :

class MyClass
{
   protected $dbh = null;

   public function __construct ( PDO $Pdh )
   {
      $this->dbh = $Pdh;
   }

   public function DoSomething($plogin_id)
   {
        $sql = "SELECT * FROM mytable WHERE login_id = :login_id";      
        $stmt = $this->dbh->prepare($sql);    //line 14
        $stmt->bindParam(':login_id', $plogin_id, PDO::PARAM_STR);
   }
}

// in your index.php
$MyObject = new MyClass ( $dbh );

, . . , .

+7

, :

global $dbh;

, , , :

class MyClass
{
    private $dbh;

    public function __construct($dbh) {
        $this->dbh = $dbh;
    }

    public function DoSomething($plogin_id)
    {
        $sql = "SELECT * FROM mytable WHERE login_id = :login_id";      
        $stmt = $this->dbh->prepare($sql);    //line 14
        $stmt->bindParam(':login_id', $plogin_id, PDO::PARAM_STR);
    }
}

:

include "config.php";
$MyObject = new MyClass($dbh); // I'm assuming $dbh is created in config.php
$login_result = $MyObject->DoSomething("admin");

, :

class MyClass
{
    public function DoSomething($plogin_id, $dbh)
    {
        $sql = "SELECT * FROM mytable WHERE login_id = :login_id";      
        $stmt = $dbh->prepare($sql);    //line 14
        $stmt->bindParam(':login_id', $plogin_id, PDO::PARAM_STR);
    }
}

:

include "config.php";
$MyObject = new MyClass($dbh); // I'm assuming $dbh is created in config.php
$login_result = $MyObject->DoSomething("admin", $dbh);
+1

:

public function DoSomething($plogin_id){
    global $dbh;
    ...

:

singleton . :

$stmt = MyDBConn::getInstance()->prepare($sql);
0

Source: https://habr.com/ru/post/1780627/


All Articles