Home > Blockchain >  Uncaught Error: Using $this when not in object context in... Help Please
Uncaught Error: Using $this when not in object context in... Help Please

Time:10-24

I have read the other posts and explored the use of $this-> & self:: but neither works on my class. I have check the recommended posts but they do not address the exact problem I am facing so my previous question was closed..... Is it because I am mixing static and not static variables in the same query?

I am not being lazy, I just truly don't understand what the problem is in order to research further. Is it the variable scope issue or a private vs. public problem. I have not seen a solution for this issue.

This is my class:

<?php 

class DBConnection {
    private $dbHost = DB_HOST;
    private $dbUser = DB_USER;
    private $dbPass = DB_PASS;
    private $dbName = DB_NAME;

    public static function make() {
        $dsn = 'mysql:host=' . $this->dbHost . ';dbname=' . $this->dbName;
        $options = array(
            PDO::ATTR_PERSISTENT => true,
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
        );
        try {
            return new PDO($dsn, $this->dbUser, $this->dbPass, $options);
        }   catch(PDOException $e) {
                die($e->getMessage());
            }
    }
}

?>

CodePudding user response:

You're using $this within a static method. Either declare your class properties as static, or remove the static from your make() function declaration.

CodePudding user response:

You are probably calling it like this DBConnection::make() Its a static function so you need to create static variables to access them, like this:

class DBConnection {
    private static $dbHost = DB_HOST;
    private static $dbUser = DB_USER;
    private static $dbPass = DB_PASS;
    private static $dbName = DB_NAME;

    public static function make() {
        $dsn = 'mysql:host=' . self::$dbHost . ';dbname=' . self::$dbName;
        $options = array(
            PDO::ATTR_PERSISTENT => true,
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
        );
        try {
            return new PDO($dsn, self::$dbUser, self::$dbPass, $options);
        }   catch(PDOException $e) {
                die($e->getMessage());
            }
    }
}

Or call it like this instead so you create a class instance:

$db = new DBConnection();
$make = $db->make();

//Remove the static and now you can use "$this->dbHost" etc..
public function make() {...}
  • Related