fork download
  1. <?php
  2.  
  3. class mysqli2
  4. {
  5. public function query($query)
  6. {
  7. return 'mysqli-query: ' . $query;
  8. }
  9. }
  10.  
  11. interface iDatabase
  12. {
  13. static public function execute($query);
  14. public function instantiatedExecute($query);
  15. }
  16.  
  17. abstract class database implements iDatabase
  18. {
  19. protected static $conn;
  20.  
  21. public static $connections = 0;
  22.  
  23. public static $objects = 0;
  24.  
  25. /**
  26.   * create an instance of database that uses the same connection across all instances
  27.   */
  28. final public function __construct()
  29. {
  30. self::$objects++;
  31. self::connect();
  32. }
  33.  
  34. /**
  35.   * Connect to a database if not already connected
  36.   */
  37. final protected static function connect()
  38. {
  39. if (null === self::$conn || false === (self::$conn instanceof mysqli2)) {
  40. echo 'Connecting to database' . PHP_EOL;
  41. self::$connections++;
  42. self::$conn = new mysqli2( /* DB info */ );
  43. //add error checking here...
  44. }
  45. return self::$conn;
  46. }
  47.  
  48. /**
  49.   * query database connection using static method
  50.   */
  51. final public function query($query)
  52. {
  53. return self::doQuery($query);
  54. }
  55.  
  56. /**
  57.   * static query database connection
  58.   */
  59. final public static function doQuery($query)
  60. {
  61. //sanitize query here if desired
  62. return self::connect()->query($query);
  63. }
  64.  
  65. }
  66.  
  67. class example extends database
  68. {
  69.  
  70. /**
  71.   * example specific static execution
  72.   */
  73. public static function execute($query)
  74. {
  75. return self::doQuery($query . ' Static');
  76. }
  77.  
  78. /**
  79.   * example specific non-static execution
  80.   */
  81. public function instantiatedExecute($query)
  82. {
  83. return $this->query($query . ' Instantiated');
  84. }
  85. }
  86.  
  87. $database = new example;
  88. $database2 = new example;
  89. $res = array(
  90. $database->instantiatedExecute('foo'),
  91. $database::execute('bar'),
  92. Example::execute('baz'),
  93. Example::execute('FOO'),
  94. $database2::execute('BAR'),
  95. $database2->instantiatedExecute('BAZ'),
  96. );
  97.  
  98. echo implode(PHP_EOL, $res) . PHP_EOL;
  99. echo database::$objects . ' total objects instantiated' . PHP_EOL;
  100. echo Example::$connections . ' total connections' . PHP_EOL;
Success #stdin #stdout 0.01s 20568KB
stdin
Standard input is empty
stdout
Connecting to database
mysqli-query: foo Instantiated
mysqli-query: bar Static
mysqli-query: baz Static
mysqli-query: FOO Static
mysqli-query: BAR Static
mysqli-query: BAZ Instantiated
2 total objects instantiated
1 total connections