PHP (Extending Classes)

Socius Decennalis
Decennium
Joined
Jun 21, 2010
Messages
325
Reaction score
54
Hello,

I cannot for the life of me, get my head around using variables from a parent class and so on. I've searched everywhere and I seriously cannot get anywhere.

Anyhow, I have a Users & Database class. Database class handles database connection and users runs queries that are relevant to users, like adding, removing and updating things and such.

I wish to extend my database class to the user class so that I am able to use the connection variable with my queries. I can't think of a better way, I'm a noobie at this still. For an example, let's say I want to get the host_info for my current connection, when in an extended class.

My Database Class:
PHP:
<?php
class Database
{
	public $connection;

	function Connect($hostname, $username, $password, $database)
	{
		return $this->connection = new mysqli($hostname, $username, $password, $database);
	}
}
?>

PHP:
<?php
class Users extends Database
{
	public $connection;

	function Connection()
	{
		return $this->connection->host_info;
	}
}
?>

I'm not sure if I would redeclare the variable to get access to it, I'm not sure what to do at this point.

PHP:
<?php
require_once("inc/classes/class.database.php");
require_once("inc/classes/class.users.php");
$database = new Database();
$users = new Users();

// Connect to database.
$database->Connect(HOSTNAME, USERNAME, PASSWORD, DATABASE);
echo $users->Connection();
?>

And this is where I would like to echo it.

I know it's connected properly, I know that for a fact, it's just I want to know how to access an extended class, pretty much my primary question.

Think anyone can help?
 
Great question.

In this scenario, you would want Users to extend Database only if Users is going to use some of the same properties/methods as Database as well as having some of its own.

PHP:
$database = new Database();
$users = new Users();

// Connect to database.
$database->Connect(HOSTNAME, USERNAME, PASSWORD, DATABASE);
echo $users->Connection();
Extended classes don't work like this. $database and $users are completely different instances. These two separate objects are not linked to each other.

PHP:
class Database
{
    public $connection;

    function Connect($hostname, $username, $password, $database)
    {
        return $this->connection = new mysqli($hostname, $username, $password, $database);
    }
}
class Users extends Database
{
    function Connection()
    {
        return $this->connection->host_info;
    }
}
You don't want/need to override $connection in Users, as it's already declared in Database and thus Users will have both the connection property and the Connect method, and of course, the defined Connection method.


Slightly unrelated note:
If you wanted to create a Connect method in the Users object, you could do so and still refer to parent properties/methods using the following syntax:
PHP:
parent::Connect
Click here for more information.
 
To add on what TimeBomb said, you might not want to extend the Database class. It won't hurt if you're only going to extend Users, but I'm pretty sure you're also planning on creating other classes that extend from the Database class. The problem is that everytime you instantiate the Users class, a new Database class is instantiated as well, coming with another database connection. You don't want more than one database connection per client connection (though there sure are exceptions).

There's several solutions to access the Database class, the most obvious being a global. I'm not sure how you feel about globals, but I personally don't like them very much (performance-wise and syntax-wise). You could also look into a singleton, but performance-wise I don't see much of a reason for that either. Leaves the best solution to my opinion: static class.

Here's a sample I wrote in the past:
PHP:
 <?php
/**
*    (C) Coypright 2013 Wizkid
*
*    Database class, this class provides basic interaction with MySQL databases
*    @author Wizkid
*     @version 1.0
*/

class Database {
    /**
     * Holds the MySQLi object
     * @access private
     * @var resource
     */    
    private static $m_pMySQLi;
    /**
     * Holds the result of the last search that was executed against the database
     * @access private
     * @var resource
     */    
    private static $m_pLastQuery;
    
    /**
      * Connect function, initializes database connection
      * @param string $strHost       Hostname of database server
      * @param string $strUsername Username to database
      * @param string $strPassword Password to database
      * @param string $strDatabase Databasename
      */
    public static function connect($strHost, $strUsername, $strPassword, $strDatabase) {
        self::$m_pMySQLi = new mysqli($strHost, $strUsername, $strPassword, $strDatabase);
    }
    
    /**
      * Returns whether or not database connection was succesful
      * @return boolean
      */
    public static function isConnected() {
        // self::$m_pMySQLi->connect_error is broken until 5.2.9 / 5.3.0
        //return (mysqli_connect_error() == "");
        return true;
    }
    
    /**
      * Returns escaped string
      * @param string $strInput The unsafe string
      * @return string
      */
    public static function escape($strInput) {
        return self::$m_pMySQLi->real_escape_string($strInput);
    }    
    
    /**
      * Executes query and saves results
      * @param string $strQuery The query to execute
      * @return resource
      */
    public static function executeQuery($strQuery) {
        return (self::$m_pLastQuery = self::$m_pMySQLi->query($strQuery));
    }
    
    /**
      * Executes query and does not cache results
      * @param string $strQuery The query to execute
      * @return boolean
      */
    public static function executeUnbufferedQuery($strQuery) {
        return self::$m_pMySQLi->real_query($strQuery);
    }
    
    /**
      * Returns single row and column from database
      * @param string $strQuery The query to execute
      * @return resource
      */
    public static function getSingle($strQuery) {
        $pResult = self::$executeQuery($strQuery);
        
        if ($pResult == null) {
            return null;
        }
        
        return $pResult->fetch_row();
    }
    
    /**
      * Returns insert id
      * @return int
      */
    public static function getInsertID() {
        return self::$m_pMySQLi->insert_id;
    }    
};
?>

Basic usage would be:
PHP:
<?php
Database::connect("localhost", "root", "root", "test");
echo Database::getSingle("SELECT * FROM temp");
?>

You can easily call connect from your basic include file and use all other functions in any class or file.
 
I've always been told to believe that globals are bad and cause unexpected results?

Update:

This is what I've come up with, this is probably a really bad example of what I'm about to show you, but however, if you think it's bad practice or it's wrong, just let me know!

This is the database class:
PHP:
<?php
class Database
{
	public $connection;

	function Connect($hostname, $username, $password, $database)
	{
		return $this->connection = new mysqli($hostname, $username, $password, $database);
	}

	function Connection()
	{
		return $this->connection;
	}
}

Example of users classes and one of the functions:
PHP:
class Users
{
	function ValidateUser($database, $inputUsername, $inputPassword)
	{
		$stmt = $database->prepare("SELECT id, username, password FROM users WHERE username = ?");
		$stmt->bind_param("s", $inputUsername);
		$stmt->execute();
		$stmt->bind_result($id, $username, $password);
		$stmt->fetch();
		if($password == $inputPassword)
		{
			return true;
		}
		else
		{
			return false;
		}
	}
}

I then call the classes and such.
PHP:
$database = new Database();
$users = new Users();

$database->Connect("localhost", "root", "", "habbodb");
$database = $database->Connection();

As you can see I pass the the current database connection through as a parameter everytime I execute a query. However, I thought this would be alright, because when a query is executed a connection has to be identified anyhow, so I didn't believe this would such a bad thing to always pass it as a parameter. As you can see, when I validate the user I pass $database, "academic", "password" onto the function. Refer to the function for more info.

PHP:
if($users->ValidateUser($database, "academic", "password"))
{
	echo "User is validated. Password is correct.";
}
else
{
	echo "User password is wrong. Access denied.";
}
 
I've always been told to believe that globals are bad and cause unexpected results?

Update:

This is what I've come up with, this is probably a really bad example of what I'm about to show you, but however, if you think it's bad practice or it's wrong, just let me know!

This is the database class:
PHP:
<?php
class Database
{
    public $connection;

    function Connect($hostname, $username, $password, $database)
    {
        return $this->connection = new mysqli($hostname, $username, $password, $database);
    }

    function Connection()
    {
        return $this->connection;
    }
}

Example of users classes and one of the functions:
PHP:
class Users
{
    function ValidateUser($database, $inputUsername, $inputPassword)
    {
        $stmt = $database->prepare("SELECT id, username, password FROM users WHERE username = ?");
        $stmt->bind_param("s", $inputUsername);
        $stmt->execute();
        $stmt->bind_result($id, $username, $password);
        $stmt->fetch();
        if($password == $inputPassword)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}

I then call the classes and such.
PHP:
$database = new Database();
$users = new Users();

$database->Connect("localhost", "root", "", "habbodb");
$database = $database->Connection();

As you can see I pass the the current database connection through as a parameter everytime I execute a query. However, I thought this would be alright, because when a query is executed a connection has to be identified anyhow, so I didn't believe this would such a bad thing to always pass it as a parameter. As you can see, when I validate the user I pass $database, "academic", "password" onto the function. Refer to the function for more info.

PHP:
if($users->ValidateUser($database, "academic", "password"))
{
    echo "User is validated. Password is correct.";
}
else
{
    echo "User password is wrong. Access denied.";
}

Yeah, passing it as a parameter would work just fine. It would however still remain a global variable and you'll have to keep passing it through, even when you're in another class that has nothing to do with the database. I recommend making the class static, which will save you a lot of parse errors as you go.
 
I use static for everything to do with classes.
I don't even do the variables.
I never pass them through constructors, or pass them as parameters.
But that's just me, work's fine for what I want to do with my scripts.

PHP:
Database::GetConnection();
PHP:
$database->GetConnection();
 
So would passing it as a parameter be an acceptable technique of accomplishing this task? Because majority of queries are "run" outside of the function, which means I can pass $database connection as a parameter. For example, I don't run a function again in the class, it is always outside the classes.
 
So would passing it as a parameter be an acceptable technique of accomplishing this task? Because majority of queries are "run" outside of the function, which means I can pass $database connection as a parameter. For example, I don't run a function again in the class, it is always outside the classes.

It's acceptable, but not recommended. Making the class static is going to save you a lot of trouble.
 
Wizkidje, I don't recommend that the entire class is static, though I do use it solely for separate connections. Below I'll explain to everyone how I tend to handle database connections with web applications.

So would passing it as a parameter be an acceptable technique of accomplishing this task? Because majority of queries are "run" outside of the function, which means I can pass $database connection as a parameter. For example, I don't run a function again in the class, it is always outside the classes.

I don't know much about your application design, but I generally use MVC.

The controller handles most of the logic and passes data to the model. The controller creates the view and passes the model to the view. The view gets data from the model on a need-to-know basis. The view also handles the view logic. The view also handles rendering the HTML and what-not.

I'm telling you this just to give you a better understanding of how I manage to get information out of the database.

The model's job is to take in data from the controller and the database as necessary and make this information available for the view to extract on a need-to-know basis (via getX methods). The model creates a MySQL object. The MySQL object is passed database arguments. The MySQL object then checks a static variable, which we'll call $connections, to see is a connection with the same host and database name already exists. If so, it uses that connection. If not, it creates the connection and stores it in the static $connections variable.

So while I may have many MySQL objects, I'll always have the minimum amount of database connections necessary throughout the application - one per host+database combination.

Here's a code snippet from my MVC framework's MySQL class that shows this (PHP 5.4):
PHP:
    /**
     * @var array
     */
    static private $connections = [];
    private $connectionKey;

    /**
     * @param string $host
     * @param string $username
     * @param string $password
     * @param string $databaseName
     * @param bool $emulatePreparedStatement
     * @throws Exception\MySQLException
     * @throws \InvalidArgumentException
     */
    public function __construct($host, $username, $password, $databaseName, $emulatePreparedStatement = true)
    {
        if (!is_string($host)) {
            throw new \InvalidArgumentException('MySQL Constructor argument 1 only accepts a string. Input type was: ' . gettype(
                $host
            ));
        }
        if (!is_string($username)) {
            throw new \InvalidArgumentException('MySQL Constructor argument 2 only accepts a string. Input type was: ' . gettype(
                $username
            ));
        }
        if (!is_string($password)) {
            throw new \InvalidArgumentException('MySQL Constructor argument 3 only accepts a string. Input type was: ' . gettype(
                $password
            ));
        }
        if (!is_string($databaseName)) {
            throw new \InvalidArgumentException('MySQL Constructor argument 4 only accepts a string. Input type was: ' . gettype(
                $databaseName
            ));
        }
        if (!is_bool($emulatePreparedStatement)) {
            throw new \InvalidArgumentException('MySQL Constructor argument 5 only accepts a bool. Input type was: ' . gettype(
                $emulatePreparedStatement
            ));
        }

        $this->connectionKey = $host . $databaseName;
        if (!array_key_exists($this->connectionKey, static::$connections)) {
            try {
                $pdo = new \PDO('mysql:host=' . $host . ';dbname=' . $databaseName, $username, $password);
                $pdo->setAttribute(\PDO::ATTR_EMULATE_PREPARES, $emulatePreparedStatement);
                static::$connections[$this->connectionKey] = $pdo;
            } catch (\PDOException $err) {
                throw new Exception\MySQLException('Error connecting to host: ' . $err->getMessage());
            }
        }
    }
 
I don't know much about your application design, but I generally use MVC.

Though MVC is definitely a good way to develop, I don't see the value of your code snippet over a static class other than yours being able to handle multiple connections at once (it'd also still maintain a global variable holding it's instance).
 
Though MVC is definitely a good way to develop, I don't see the value of your code snippet over a static class other than yours being able to handle multiple connections at once (it'd also still maintain a global variable holding it's instance).

The object that I use does not suffer anywhere near as much from the many problems globally scoped classes can cause. There are still some potential issues though, given the static variable. This could be fixed by adding another argument to the constructor, telling it to store the connection only in the instance, rather than retrieving it from or setting it to the static instance.

In regards to the specific issues that working in the global scope, as you are suggesting, can cause, I would once again recommend you muse over the links in my previous post, quoted below:
 
The object that I use does not suffer anywhere near as much from the many problems globally scoped classes can cause. There are still some potential issues though, given the static variable. This could be fixed by adding another argument to the constructor, telling it to store the connection only in the instance, rather than retrieving it from or setting it to the static instance.

I was referring to static classes being much more faster than singletons, wasn't referring to problems they can cause, though I really can't think of any (and your sources didn't state any as far as I'm aware).
 
Static classes are fine if you know it will be needed in a global scope just one time. A class called Database has to be non-static, since your project could work with more than one database.
Although I want to mention that a class named Database should be a domain object. Means it should not contain any logic, it should contain a list of Table. So Database is the wrong name and references to a framework such as an entity framework.
The correct spelling would be {DBNAME}Manager. Due the fact it has the exact database name in it doing it static would be fine, more correct would be a static manager class for every table. Those static classes should never contain any static properties and only set data via method arguments or retrieve data via return values.
It would be fine to store the connection to the database in any way statically, but you must prevent you connect or store it two times by 100%!

Sense of the above is to split of existing items (database, tables, data sets, ...) from its logic (load, save, find, ...) as well as you should spit this all off the browser code (html, css, js).

Usually a singleton class is only recommend in case of a needed limited scope for a static class or to prevent any memory reservation of the class when it has not been initiated.
 
I was referring to static classes being much more faster than singletons, wasn't referring to problems they can cause, though I really can't think of any (and your sources didn't state any as far as I'm aware).

The links that I provided detail over many of the issues with static classes and the global namespace. It's not about speed, as in this day and age, code is fast unless you design it incredibly poorly. It's about application design. Note that the code that I described and provided a snippet of is not technically a singleton.

Static classes are fine if you know it will be needed in a global scope just one time. A class called Database has to be non-static, since your project could work with more than one database.
Although I want to mention that a class named Database should be a domain object. Means it should not contain any logic, it should contain a list of Table. So Database is the wrong name and references to a framework such as an entity framework.
The correct spelling would be {DBNAME}Manager. Due the fact it has the exact database name in it doing it static would be fine, more correct would be a static manager class for every table. Those static classes should never contain any static properties and only set data via method arguments or retrieve data via return values.
It would be fine to store the connection to the database in any way statically, but you must prevent you connect or store it two times by 100%!

Sense of the above is to split of existing items (database, tables, data sets, ...) from its logic (load, save, find, ...) as well as you should spit this all off the browser code (html, css, js).

Usually a singleton class is only recommend in case of a needed limited scope for a static class or to prevent any memory reservation of the class when it has not been initiated.
Class naming structure is up to the programmer and there is no correct or unanimously valid naming pattern, although there are numerous popular coding standards that define them, to an extent.

In regards to creating a static class or not, you shouldn't in most scenarios (at least when using PHP). This is a subject that has been gone over time and time again by many, many people, hence why I linked four separate pieces of information in my previous post.
 
Last edited:
Update:

I've come to the conclusion that this is best way. But I'm just curious as to why this works and the other option I had in mind isn't working. So the class below is the one that works perfectly and I can use it across all classes.
PHP:
class Database
{
	public static $connection;

	private $connected = false;
	private $hostname;
	private $username;
	private $password;
	private $database;
	public function __construct($hostname, $username, $password, $database)
	{
		$this->hostname = $hostname;
		$this->username = $username;
		$this->password = $password;
		$this->database = $database;
		self::$connection = new mysqli($this->hostname, $this->username, $this->password, $this->database);
	}
}
I can then call the static variable connection and I'm able to use it. However, let's say I want to extend the mysqli class and use the parents (mysqli class) class constructor to do that, so it's looks even more classy. However, it won't work, here it is.

PHP:
class Database extends mysqli
{
	public static $connection;

	private $connected = false;
	private $hostname;
	private $username;
	private $password;
	private $database;
	public function __construct($hostname, $username, $password, $database)
	{
		$this->hostname = $hostname;
		$this->username = $username;
		$this->password = $password;
		$this->database = $database;
		self::$connection = parent::__construct($this->hostname, $this->username, $this->password, $this->database);
	}
}

It just returns null and literally the $connection variable just doesn't get set, so it's safe to say it's not accessing the parents class correctly. Anyhow, I'm just curious to why it won't work, however I'm not using it. So don't stress.

But what does everyone think of the top class, that's the one I'm thinking of using?
 
Last edited:
Back