BryanLavinParmenter
BryanLavinParmenter

Reputation: 416

PHP OOP use extends class in functions

Here's my current code

class Database {
    //Connect to database here...
}

class User extends Database {

    public function GetUInfo($id) {
        $db = new Database;
        $db->query("SELECT `id` FROM `users` WHERE `id`=:id");
        $db->bind(":id", $id);
        return $db->single();
    }

    public function uptime($id) {
        $db = new Database;
        $db->query("UPDATE `users` SET `time`=".$_SERVER['REQUEST_TIME']." WHERE `id`=:id");
        $db->bind(":id", $id);
        return $db->execute();  
    }

}

In the User class, how can I make it so that $db = new Database; is ready in all of the public functions, instead of having to add $db = new Database; in each of the functions?

Upvotes: 1

Views: 147

Answers (2)

Anand Patel
Anand Patel

Reputation: 3943

As you have extends Database Class into User why you are creating objects ? you can directly access functions(public and protected) of Database Class

you can directly access it using $this keyword.

only you have to make connection in Constructor(parent class) and in child class you have to call parent class constructor.

<?php
class Database
{
    protected $db;

    public function __construct()
    {
        //your connection code
    }
}

class User extends Database
{

    public function __construct()
    {
        parent::__construct();
    }

    public function GetUInfo($id)
    {
        $this->query("SELECT `id` FROM `users` WHERE `id`=:id");
        $this->bind(":id", $id);
        return $this->single();
    }

    public function uptime($id)
    {
        $this->query("UPDATE `users` SET `time`=".$_SERVER['REQUEST_TIME']." WHERE `id`=:id");
        $this->bind(":id", $id);
        return $this->execute();
    }
}

?>

Upvotes: 2

Peter Popelyshko
Peter Popelyshko

Reputation: 363

Create a constructor and private property $db

private $db;

public function __construct() {
  $this->db = new Database();
}

So you can use it like this

   public function uptime($id) {
        $this->db->query("UPDATE `users` SET `time`=".$_SERVER['REQUEST_TIME']." WHERE `id`=:id");
        $this->db->bind(":id", $id);
        return $this->db->execute();  
    }

As metioned mTorres its better to do like this

public function __construct(Database $db) { $this->db = $db; }

If you are new to OOP - read this article it might help.

Upvotes: 2

Related Questions