-1

So I have a Database class with a function like this:

public function sql($sql) {
    $result = $this->connection->query($sql);
    return $result;
}

But it returns the error:

Fatal error: Uncaught Error: Using $this when not in object context

But I don't get it why I get this error, I've looked al around the internet, but nobody seems to have this exact problem.

This is my full database class:

namespace Core;

require_once ("../config.php");

class DB {

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

    public function connection() {
        $this->connection = new \mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);

        if ($this->connection->connect_error) {
            die("Database fout");
        }
    }

    public function sql($sql) {
        $result = $this->connection->query($sql);
        return $result;
    }
}

Then I call it like so:

DB::sql('SELECT * FROM `users`');

But then I get the error. :/

Manoj Sharma
  • 1,467
  • 2
  • 13
  • 20
Luuk Wuijster
  • 6,678
  • 8
  • 30
  • 58

1 Answers1

2
DB::sql('SELECT * FROM `users`');

This is static function call method and in static function you can't use $this You need to call like

$database = new DB();
$sql = $database->sql('SELECT * FROM `users`')

In that case according to your comment your class should look like

<?php
namespace Core;

require_once ("../config.php");

class DB
{
    public static $connection;

    public static function connection()
    {
        self::$connection = new \mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
        if (self::$connection->connect_error) {
            die("Database fout");
        }
    }
    public static function sql($sql)
    {
        $result = self::$connection->query($sql);
        return $result;
    }
}
DB::connection();
Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
M A SIDDIQUI
  • 2,028
  • 1
  • 19
  • 24