SitePoint Sponsor

User Tag List

Results 1 to 9 of 9
  1. #1
    SitePoint Member
    Join Date
    Sep 2006
    Posts
    21
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    __construct() purpose

    Hey

    I'm fairly new to OOP programming but I'm having a hard time understanding what __construct() does.

    For example, I want to write a MySQL class, would I do this:

    PHP Code:
    <?php
    class mysql
    {
        
        private 
    $databaseName;
        private 
    $databaseHost;
        private 
    $databaseUser;
        private 
    $databasePass;
        
        function 
    __construct($databaseName$databaseHost$databaseUser$databasePass)
        {
            
    mysql_connect($database .. etc)
        }
        
    }
    ?>
    Or do I simply just do function connect($databaseName) .. etc

    It wouldn't suprise me if I'm not supposed to do either

    Can anyone shed some light?

  2. #2
    SitePoint Evangelist
    Join Date
    Aug 2007
    Posts
    566
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    A constructor is a method inside an object that is called when the object is instantiated (created).
    It's not mandatory, but you would use it to initilize properties (variables) in the object, or in your case, instantiate a conection to the DB.

    In your specific case, the best practices would be that you create a static method called connect(), and call that method from the constructor:
    http://www.php.net/manual/en/language.oop5.static.php
    PHP Code:
    <?php
    class mysql{
        private 
    $databaseName;
        private 
    $databaseHost;
        private 
    $databaseUser;
        private 
    $databasePass;
        
        public function 
    __construct(){
            
    //we call a static method this way: class name :: method()
            
    mysql::connect()
        }
        
        public static function 
    connect(){
          
    mysql_connect(self::database.. etc)
        }
    }
    ?>

  3. #3
    SitePoint Wizard silver trophybronze trophy Cups's Avatar
    Join Date
    Oct 2006
    Location
    France, deep rural.
    Posts
    6,869
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    Not sure I understand that reply. How does the class get its credentials?

    The difference is with a connect() method added like that is that you now have to do this:

    $db = new mysql;
    $db->connect();

    Whereas before all you had to do was:

    $db = new mysql("xxxx","yyy","zz");

    In which situation do you think you'd find yourself instantiating a mysql class, and yet not connecting to the database server?

    To answer your question, you see this:

    $db = new mysql("xxxx","yyy","zz");

    is the equivalent of:

    $db = new mysql ;
    $db->__construct("xxxx","yyy","zz");

  4. #4
    play of mind Ernie1's Avatar
    Join Date
    Sep 2005
    Posts
    1,252
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    PHP Code:
    // To access a member variable from within a member function,
    // you must use the special variable (also called a pseudo-variable) $this.
    // It refers to the current instance of the object itself.
    // You combine it with the dereferencing operator (->) to access the member variables.

    class mysql
    {
        private 
    $databaseHost$databaseUser$databasePass$databaseName$link_id;

        function 
    __construct$databaseHost$databaseUser$databasePass$databaseName )
        {
            
    // these variables are equal to the __construct function arguments
            
    $this->databaseHost $databaseHost;
            
    $this->databaseUser $databaseUser;
            
    $this->databasePass $databasePass;
            
    $this->databaseName $databaseName;

            
    $this->connect();
        }

        public function 
    connect()
        {
            
    $this->link_id mysql_connect$this->databaseHost$this->databaseUser$this->
                
    databasePass );
            if ( ! 
    $this->link_id )
            {
                
    $this->oops"Could not connect to server" );
            }

            if ( ! 
    mysql_select_db($this->databaseName$this->link_id) )
            {
                
    $this->oops"Cannot open database" );
            }
        }

        public function 
    oops$msg '' )
        {
            if ( 
    $this->link_id )
            {
                
    $this->error mysql_error$this->link_id );
                
    $this->errno mysql_errno$this->link_id );
            }

            
    $this->error mysql_error();
            
    $this->errno mysql_errno();

            echo 
    $msg;

            if ( 
    strlen($this->error) > )
                echo 
    $this->error;
        }
    }

    // instantiate
    $mysql = new mysql"localhost""root""password""database" ); 
    my mobile portal
    ghiris.ro

  5. #5
    SitePoint Wizard bronze trophy
    Join Date
    Jul 2008
    Posts
    5,757
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    The constructor is used to initialize the state of the object. People often set default values to variables, or accept some client input through the constructor, and set some of it to instance variables. Basically it prepares to object to be used by the client(the client meaning the client program, eg the code which is using this class).

  6. #6
    SitePoint Evangelist
    Join Date
    Aug 2007
    Posts
    566
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    In which situation do you think you'd find yourself instantiating a mysql class, and yet not connecting to the database server?
    I was not talking about this class in particular, but object in general.
    Sure, you can keep the db connections paramters in the constructor.

    In that case, what I would do would be to set the class private properties with them, and then call the connect() methos, without passing again the values.

    I even go a bit further, as I usually have a "globals.php" file included before each request, that define the value for the connection to the db.
    Then, the db layer object just use the values I've defined previously.

    Variables are local to their execution level, but defines are visible on every scopes. Even in classes.
    globals.php:
    PHP Code:
    define('DB_HOST','127.0.0.1');
    define('DB_NAME','test');
    define('DB_PWD','pwd');
    define('DB_USER','user'); 
    clMysql.php:
    PHP Code:
    <?php
    class clDb extends clBaseDb{
        
    /**
        * Constructor, will instanciate a db connection
        * 
        */
        
    public function __construct(){
            
    $this->init();
        }
        
        
    /**
         * prepare a set of datas to be binary safe
         * @param String $data
         * @return String The binary encoded datas
         */
        
    public function setBinary($datas){
            return 
    mysql_real_escape_string($datas);
        }

        
    /**
        * This method will create a connection to the db.
        * 
        */
        
    protected function init(){
            
    $host=DB_HOST;
            
    $user=DB_USER;
            
    $pass=DB_PWD;
            
    $db=DB_NAME;
            
    $this->_db=new PDO("mysql:host=$host;dbname=$db"$user$pass, array( PDO::ATTR_PERSISTENT => PDO_CONN_PERSIST));
        }
        
    }
    ?>

  7. #7
    Theoretical Physics Student bronze trophy Jake Arkinstall's Avatar
    Join Date
    May 2006
    Location
    Lancaster University, UK
    Posts
    7,062
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Which, of course, stops any chances of using multiple databases

    Whilst it's best to stick to just one DB, it's also best to make your classes able to be different from eachother. Whats the point in a db object if it can't be used with different databases within one run?
    Jake Arkinstall
    "Sometimes you don't need to reinvent the wheel;
    Sometimes its enough to make that wheel more rounded"-Molona

  8. #8
    SitePoint Wizard silver trophybronze trophy Cups's Avatar
    Join Date
    Oct 2006
    Location
    France, deep rural.
    Posts
    6,869
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    Ernie1 had the best reply, you can use the constructor to assign some necessary properties and even get it to fire off some methods for you.

    He also dealt with the thorny issue of "what happens if all does not go as planned?".

    Off Topic:



    $this->databaseHost = $databaseHost;

    One feature of classes is encapsulation - so you can just as easy use:

    $this->host = $host;

    Anyway, you've declared them private - so they will never be seen/used anywhere else.

    Its in a class called mysql so I'd have thought that $database prefixes is just extra typing, extra chance of getting it wrong and less readability. But others may disagree.

  9. #9
    SitePoint Evangelist
    Join Date
    Aug 2007
    Posts
    566
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by arkinstall View Post
    Which, of course, stops any chances of using multiple databases

    Whilst it's best to stick to just one DB, it's also best to make your classes able to be different from eachother. Whats the point in a db object if it can't be used with different databases within one run?
    Because it's a wrapper, as I have for postgresql, oracle, ms sql server and sqlite.
    The base is stored in the clBaseDb object.
    The only time I needed several db connections, I tweaked it to use distinct defines.

    I did it that way because it's the way I use it 99.99% of the time.
    I will not complexify my objects to handle those very specific cases.


Bookmarks

Posting Permissions

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