user656925
user656925

Reputation:

Where can I close the mysql connection in this class hierarchy?

I have 4 classes in PHP I use to signup a user, problem is I don't know how to close the mysql connection.

Class calls:

single_connect->database->post->signup

When I implement mysql_close() in the singleton it breaks my code. My assumption is that as long as a signup object is created the classes it extends from are also "instantiated". But this does not appear to be the case.

I had to comment out the mysql_close to allow this to work. Note that my singleton uses the database link to determine if it exists wrather then a pointer to itself like most Singletons.

/*single_connect*/

class single_connect
  {
  private static $_db_pointer = NULL;
  private function __destruct() 
    {
    //mysql_close();
    }
  private function __construct()
    {
    self::$_db_pointer = mysql_connect(DB_HOST, DB_USER, DB_PASS);
    mysql_select_db(DB_DATABASE);
    }
  public static function get_connection()
    {
    if(self::$_db_pointer == NULL)
      {
      return new self();
      } 
    }
  }

/*database*/

abstract class database
  {
  protected function __construct()
    {
    single_connect::get_connection();
    }
  protected static function query($query)
    {
    $result = mysql_query($query) or die(mysql_error());
    return $result;
    }
  }

/*post*/

class post extends database
  {
  public $_protected_arr=array();
  protected function __construct()
    {
    parent::__construct();
    $this->protect();
    }
  protected function protect()
    {
    foreach($_POST as $key => $value)
      {
      $this->_protected_arr[$key] = mysql_real_escape_string($value);
      }
    }
  }

/*signup*/

class signup extends post 
  { 
 ...

Upvotes: 1

Views: 150

Answers (2)

Alan B. Dee
Alan B. Dee

Reputation: 5616

I found the problem. In my explanation about Singleton classes and static properties I checked how PHP handles static properties.

"Like any other PHP static variable, static properties may only be initialized using a literal or constant; expressions are not allowed. So while you may initialize a static property to an integer or array (for instance), you may not initialize it to another variable, to a function return value, or to an object." http://php.net/manual/en/language.oop5.static.php

You cannot set the static property as an object like you can in C++, Java or most other OOP languages. In this case the connection was being closed when the class was GC'ed.

My apologies to prodigitalson, I was incorrect in my comments.

Upvotes: 0

wonk0
wonk0

Reputation: 13972

Connections are automagically being closed when script execution finishes. So if there is no tremendous amount of time between the last database operation and the end of the script I would not bother to explicitly close the connection.

Upvotes: 2

Related Questions