0

I have a class responsible for connecting to the database and it returns the connection itself in the construction method

How can I use it inside a static class?

Database.php

<?php


class Database {

    private $host = "localhost";
    private $usuario = "root";
    private $senha = "";

    protected $connection;

    public function __construct()
    {
        if(!isset($this->connection))
        {
            $this->connection = new mysqli($this->host, $this->usuario, $this->senha, "netflix_cards", 3308);
            mysqli_set_charset($this->connection, "utf8");
            if(!$this->connection) {
                echo 'Não foi possível conectar ao banco de dados';
                exit;
            }

            return $this->connection;
        }
    }

    public function query($query)
    {
        return $this->connection->query($this->connection->real_escape_string($query));
    }
?>

User.php

<?php


class User {

    static function register() {
        
    }
}
Dharman
  • 30,962
  • 25
  • 85
  • 135
StackPHPcRoW
  • 61
  • 1
  • 4

1 Answers1

0

Best practice is to avoid purely static class and the singleton pattern (see answer here : PHP singleton database connection pattern

You should instantiate User with new, and dependancy-inject an instantiated database connection that you pass around as a parameter where needed.

As someone noted, you should first make your Database work properly.

smwhr
  • 675
  • 6
  • 22