Page 1 of 1

Passing variables to PDO via singleton

Posted: Tue Jun 08, 2010 7:17 am
by steel_rose
Hi everybody,

I'm trying to pass some variables collected by a form (dsn settings, user and password) to a singleton that should open a connection to a database.
The class is based on some O'Reilly code but, as it didn't do what I was looking for, I also used what was discussed on this forum here:
viewtopic.php?f=1&t=103832&p=555537&hil ... on#p555537

For this code:

Code: Select all

<?php
class DBCxn {
    
    
    public static function setValues($dsn, $username, $userpass){
          $self = self::getInstance();
          $self->$_SESSION['dsn'] = $dsn; 
          $self->$username = $_POST['username'];
          $self->$userpass = $_POST['userpass'];
    }

    
    //internal variable to hold the connection
    private static $dbh;
    
    //no cloning or instantiation allowed
    final private function __construct(){ }
    final private function __clone(){ }
     
    public static function get () {
        
        //connect if not already connected
        if (is_null(self::$dbh)) {
            setValues(); 
            self::$dbh = new PDO(self::$dsn, self::$username, self::$userpass);
        }
        
        //return the connection
        return self::$dbh;
    }
}

//form to collect info, etc..

$dbh = DBCxn::get($dsn, $username, $userpass);

?>

I get this error:

[text]
Fatal error: Call to undefined function setValues() in /opt/lampp/htdocs/xampp/codershed.co.uk/dbcxn.php on line 25
[/text]

I tried many different solutions, but I don't seem to be able to make this work... does anyone have any suggestion?

Thank you for your time!

SR

Re: Passing variables to PDO via singleton

Posted: Tue Jun 08, 2010 9:27 am
by markusn00b
You need to tell PHP that the method is part of a class, otherwise it just looks in the global function table.

Code: Select all

self::setValues();