views:

65

answers:

1

Hello,

I am still looking for a way to phrase it properly (I'm not a native speaker...).

So I have this class SQL which implements the singleton pattern (for obvious reasons) and I also have this function, checkUsr(), which queries the database using one of SQL's methods.

Everything works fine as long as I don't call checkUsr() from within the SQL class. When I do so, the scripts just exits and a blank page is displayed - no errors are returned, no exception is thrown... What's happening? And how do I work around this problem?

EDIT:

some code here:

class SQL
{
  public static function singleton()
  {
    static $instance;
    if(!isset($instance))
      $instance = new SQL;
    return $instance;
  }

  public function someOtherFun()
  {
    checkUsr();
  }

  public function tryLoginAuthor( $login, $sha1 )
  {
    // SQL query
  }
}

function checkUsr()
{
    if (!isset($_SESSION['login']) || !isset($_SESSION['sha1']))
        throw new Exception('Not logged in', 1);
    $SQL = SQL::singleton();
    $res = $SQL->tryLoginAuthor($_SESSION['login'], $_SESSION['sha1']);
    if (!isset($res[0]))
      throw new Exception('Not logged in', 1);
}

So the problem occurs, when I call checkUsr from within the SQL class. It does not, however, happen when called from some other class...

A: 

You have to turn on error_reporting, to see the error messages by php, otherwise you will get the blank page you describe. At the top of your index.php file, include these:

ini_set('display_errors', true);
error_reporting(E_ALL | E_STRICT);

Don't forget to turn it off in your production machine, this is only for development.

You have declared the variable $instance, as static inside the function, instead of inside class. These are two completely different things. See the usage of static variables here, and see the usage of a static class property here. You need the latter, so change your code to this:

class SQL {
    static $instance;
    public static function singleton()
      {
        if(!isset(self::$instance))
          self::$instance = new SQL;
        return self::$instance;
      }
...

}

Implementing a SQL class, or any kind of database access as a singleton is a very bad idea, it's going to bite you very hard in the long run. If it turns out that you need to support another database, like you need to pull information from a forum, that is in a different DB than your site, you will have serious problems.

WishCow
I do use custom error reporting and exception handling, which (whilst in developer's environment) simply outputs whatever may come. However, you've got the point about the variable scope - though it doesn't seem to be the problem. I resolved the problem by some workaround for now and will look more into it later on. However, thanks for your help - though I disagree on using singleton SQL classes, but that'd be a much longer debate ;)
dare2be
There was an error in the singleton function it's fixed now.
WishCow