Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New Coder
    Join Date
    Feb 2006
    Posts
    44
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Private constructor (singleton)

    I am trying to make a class just for connecting to the MySQL and I want to make it a singleton because only one connection should ever be needed at a time.

    Heres what I have (a simplified version)

    PHP Code:
    $host="myhost";
    $database="mydb";
    $user="myusername";
    $pass="mypass";

    class 
    mysqlcon{

        private static 
    $instance NULL;

    private function 
    __construct($host$user$pass){
           
    //Construct stuff here
    }

    static public function 
    getInstance($host$user$pass){
          
    // getInstance stuff here
    }

    }

    $con = new mysqlcon::getInstance($host$user$pass); 
    However when I do that last line to create the instance of the object, I get

    Fatal error: Call to private mysqlcon::__construct() from invalid context

    So I just want to know how I Can call the singleton class properly?
    Last edited by marf; 03-19-2007 at 06:37 PM.

  • #2
    New Coder
    Join Date
    Feb 2006
    Posts
    44
    Thanks
    0
    Thanked 0 Times in 0 Posts
    I figured it out with a little searching around.


    If anybody wants to know for the future,
    when you call the class you don't need new ClassName, because you only want one instance of the class to begin with.

    so the working code for me was

    PHP Code:
    $con mysqlcon::getInstance($host$user$pass); 
    enjoy!


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •