Calling a class inside another in PHP

I hope you can help me with this: I have two classes: database and users. The database is connected to the database using PDO (inside the constructor) and has functions for changing tables, inserting data, etc. The Users class will process the login, as well as add / remove users. However, the Users class needs to connect to the database. How can i do this?

+3
source share
5 answers

There are a few things you could do:

Globals

$db = new Database();

class Users
{
  public function foo()
  {
    global $db;
    $db->query();
  }
}

Setting a static variable

$db = new Database();

class Model
{
  static public $db;
}

Model::$db = $db;

class Users extends Model
{
  public function foo()
  {
    self::$db->query();
  }
}

Use singleton

class Database
{
   private static $instance;

   private function __construct()
   {
   }

   public static function instance()
   {
      return self::$instance ? self::$instance : self::$instance = new self();
   }
}

class Users
{
   public function foo()
   {
      Database::instance()->query();
      // or $db = Database::instance(); $db->query();
   }
}

The only thing you want to avoid is to create a new database connection for each model or class.

+10

Users:

class Users  {
  var $database;
  function __construct()  {
    $this->database = new Database();
  }
};

, , .

+1

, , :

<?php
class Users
{

    protected $_db;

    public function __construct(Database $database = null)
    {
        if (!$database) {
            $database = new Database;
        }
        $this->_db = $database;
    }

    public function addUser($username)
    {
        // Do stuff ...
        $this->_db->insert($data);
    }

}

User, :

<?php
$users = new Users;
$users->addUser('joebob');
+1

- , , .

, , ( ).

$DB = new Database();

$GLOBALS:

class User {
  function __construct() {
    $DB = &$GLOBALS['DB'];
    // do something
    $DB->callSomeMethod();
  }
  ...
}

As @Ryan pointed out, namespace conflicts are possible using this strategy. The best middle way is to convert the database class to a singleton. Then it will save its own instance (translation: ONE connection no matter what), which can be accessed using the Database :: getInstance () method.

+1
source

This is my user class:

class Users {

    private $data;
    private $db;

    public function __construct() {
        $db = Database::getInstance('localhost', 'database', 'root', '123456');
    }

    public function __get($key) {
        return $this->data[$key];
    }

    public function __set($key, $value) {
        $this->data[$key] = $value;
    }

    public function test() {

        foreach($this->db->query('table', '*', '', '', '', '', '0,5') as $value) {
            $results .= $value['field1'] . "<br />";
        }

        return $results;
    }
}
0
source

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


All Articles