<?php
class mysqli2
{
public function query($query)
{
return 'mysqli-query: ' . $query;
}
}
interface iDatabase
{
static public function execute($query);
public function instantiatedExecute($query);
}
abstract class database implements iDatabase
{
protected static $conn;
public static $connections = 0;
public static $objects = 0;
/**
* create an instance of database that uses the same connection across all instances
*/
final public function __construct()
{
self::$objects++;
self::connect();
}
/**
* Connect to a database if not already connected
*/
final protected static function connect()
{
if (null === self::$conn || false === (self::$conn instanceof mysqli2)) {
echo 'Connecting to database' . PHP_EOL;
self::$connections++;
self::$conn = new mysqli2( /* DB info */ );
//add error checking here...
}
return self::$conn;
}
/**
* query database connection using static method
*/
final public function query($query)
{
return self::doQuery($query);
}
/**
* static query database connection
*/
final public static function doQuery($query)
{
//sanitize query here if desired
return self::connect()->query($query);
}
}
class example extends database
{
/**
* example specific static execution
*/
public static function execute($query)
{
return self::doQuery($query . ' Static');
}
/**
* example specific non-static execution
*/
public function instantiatedExecute($query)
{
return $this->query($query . ' Instantiated');
}
}
$database = new example;
$database2 = new example;
$database->instantiatedExecute('foo'),
$database::execute('bar'),
Example::execute('baz'),
Example::execute('FOO'),
$database2::execute('BAR'),
$database2->instantiatedExecute('BAZ'),
);
echo implode(PHP_EOL
, $res) . PHP_EOL
; echo database::$objects . ' total objects instantiated' . PHP_EOL;
echo Example::$connections . ' total connections' . PHP_EOL;