www.webdeveloper.com
Results 1 to 2 of 2

Thread: why use __construct()?

  1. #1
    Join Date
    Dec 2013
    Posts
    57

    why use __construct()?

    I have read the php manual as well as a stackoverflow question about the __construct() method. I still can not understand what it does and what is the reason for it. Can someone break it down for me?

  2. #2
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    19,523
    It is a method that automatically gets called any time you create a new instance of that class, so you define it if there is any processing that needs to happen upon creation of an object (i.e. use the "new" keyword). Similarly, there is a __destroy() method that gets called whenever that object is unset() or otherwise destroyed, though that tends to be much less used than __construct() (with most classes, programmers don't really care what happens when the object is no longer needed).

    __construct() is often used to populate data required for an object, forcing the calling code to supply required parameters, rather than depending on it to specifically call one or more other methods to do so. For example, if my Foo class needs a PDO object to do its database operations, I can make it a required parameter of the __construct method:
    PHP Code:
    class Foo
    {
        private 
    $pdo;

        public function 
    __construct(PDO $pdo)
        {
            
    $this->pdo $pdo;
        }

        
    // other methods, some of which use $this->pdo...
    }

    // this will work:
    $db = new PDO($dsn$user$pass);
    $good = new Foo($db);

    // this will cause a fatal error:
    $bad = new Foo();

    // this will also fail:
    $db "not a PDO object";
    $oops = new Foo($db); 
    "Please give us a simple answer, so that we don't have to think, because if we think, we might find answers that don't fit the way we want the world to be."
    ~ Terry Pratchett in Nation

    eBookworm.us

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

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



Recent Articles