user3057514
user3057514

Reputation: 261

Unable to pass variable from function to class

I have a db connect function and an abstract database class bause of the way I structure it. I have to keep added my PDO connect codes to the constructor.

My config.php I have

function dbconnect() 
{
            $dbh; // database handler
             $host = 'localhost';
             $user =  'root';
             $pass =  '';
             $dbname = 'test101';
             $error;
                // Set DSN
                $dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname;
                // Set options
                $options = array(
                    PDO::ATTR_PERSISTENT    => true,
                    PDO::ATTR_ERRMODE       => PDO::ERRMODE_EXCEPTION,
                    PDO::ATTR_EMULATE_PREPARES => false

                );
                // Create a new PDO instanace
                try{
                    $this->dbh = new PDO($dsn, $this->user, $this->pass, $options);
                }
                // Catch any errors
                catch(PDOException $e){
                    $this->error = $e->getMessage();
                }

           }

in my abstract.class.php

 include_once('config/config.php');

class Database {


           public function __construct() {
               dbconnect(); //connect to database

           }

           public function query($query) {
               $this->stmt = $this->dbh->prepare($query);
           }

}
$database = New Database();

not in config.php I have a dtabase handler $dbh and in abstract.class.php I am calling its in the query function.

My question

I am getting an error Undefined property: Database::$dbh. how can I pass this from my config.php to abstract.class.php? I thought when you using the PHP include this is the same as copying and paste whatever is in that file in the file you want to use it for. How can I pass $dbh from config.php to abstract.class.php please feel free to advice me on anything issues that might happen, or anything with my PDO connection that will do with security issues.

This works if I copy and pass my function in the constructor and set the database connection variables to private $dbh; outside the constructor but the issue with this is the fact of always having to include the class when I dont every need it. sometimes I might just need to connect to the database also I wanted to add define salt to the config.php

Upvotes: 0

Views: 101

Answers (1)

Mazzy
Mazzy

Reputation: 1944

In your database class you are calling $this->dbh, so in your dbconnect function, return $dbh, then in the database class constructor: $this->dbh = dbconnect();

Upvotes: 1

Related Questions