Jump to content

constructor? __construct


DarnJhud
 Share

Recommended Posts

Hi everyone,

 

I just started learning php and I am now on the OOP part. (bought a book for dummies and it's 7 in 1 web programming, it did not discuss much further about constructor though and can't find it in w3schools ) what I don't understand is the function of __construct. Is it required that every time I'm gonna create a class there should be a constructor.

 

I mean I know it's not required literally. I've been creating simple class without constructor and it's perfectly running. But I remember reading it somewhere that it's a good practice to have constructor in your class.

Is that legit? If it is why? what is this constructor for??

Edited by DarnJhud
Link to comment
Share on other sites

If it is why?

It is good pracitice because it helps to property initialization when object creates. You can give only scalar values and arrays as default to properties, but not reference type like object.

  • Like 1
Link to comment
Share on other sites

If it is why?

It is good pracitice because it helps to property initialization when object creates. You can give only scalar values and arrays as default to properties, but not reference type like object.

 

 

-- sir correct me if I'm wrong so the constructor is executed when an object is created using the class with the __construct inside.

So what is the most common thing we want the constructor do when we create an object? a simple example will help me better understand this constructor.

 

Constructors in object-oriented programming are meant to set things up when an object is created. W3Schools' PHP tutorial is incomplete, you can learn from the PHP manual.

 

-- sir so in the book im reading there should only be 1 constructor per class, but in the manual we can have multiple constructor.. why would we want many constructor in our class?and thank you both for your answers earlier.. I really appreciate your time :)

Link to comment
Share on other sites

Right, when you create a new object, e.g.:

 

$db = new mysqli();

 

then the class constructor gets executed once the new object instance gets created. The most common thing that constructors are used for is probably to initialize various non-constant properties of the object. Like the manual for properties says:

 

 

 

This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.

 

Look at example 1 on that page to see examples of invalid and valid property declarations. If your class has properties that need to be initialized to non-constant values, you do that in the constructor.

 

Often creating an object also involves passing arguments when you create the object, e.g.:

 

$db = new mysqli($host, $username, $password, $database);

 

You're passing 4 arguments to the constructor, so the constructor needs to save or use those values.

 

http://www.php.net/manual/en/mysqli.construct.php

 

 

 

but in the manual we can have multiple constructor

No, classes in PHP can only have a single constructor. You might have a class that extends or inherits from other classes or interfaces, and each of those can have their own constructor, but a single class wouldn't have more than one. Other languages allow different kinds of constructors, for example a copy constructor that would get executed if you created a copy of the object.

 

The class can also have a destructor that gets executed when the object gets destroyed if you need to do anything to clean up. Destructors aren't used a whole lot, one time I can think of having used a destructor was for a class that manages the configuration options for an application. When you create the class you can do things like get the current value of an option or change the value. Instead of updating the database immediately whenever you change a value, I had it keeping track of which values got changed and then the destructor checked for that and updated the database if anything was changed during the script. Here's an example:

<?php class app_config{  private $fields;  private $dirty;  private $db;  private $debug;  private $fpath;  private $db_keys;   function __construct()  {    global $db;    /*    Why it is necessary to keep a reference to global db:       This class uses the db object in the destructor.  There is no guarantee      which order objects will get destroyed in.  An object will not get destroyed      if there are references to it somewhere else.  Storing a reference to the      global db object in this class ensures that this object will be available      for the destructor to use.       A side-effect of this is that this class requires the db object to have      already been created when an object of this class is instantiated.    */     $this->debug = false;    $this->fpath = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'config.log';     $this->fields = array();    $this->dirty = array();    $this->db_keys = array();    $this->db = $db;     if ($this->debug)      file_put_contents($this->fpath, date('r') . " Config class createdn", FILE_APPEND);  }   function __destruct()  {    # commit changes    $tmp = array();    foreach ($this->dirty as $k => $v)    {      $tmp[] = $k;      $update = array('val' => $this->fields[$k]);      if (in_array($k, $this->db_keys))        $this->db->update('config', $update, "`name`='{$k}'");      else        $this->db->insert('config', array('name' => $k, 'val' => $this->fields[$k]));    }    if ($this->debug)      file_put_contents($this->fpath, date('r') . " Config class destroyed.  Updates:n" . print_r($tmp, true), FILE_APPEND);  }   function get_opt($id)  {    if ($this->debug)      file_put_contents($this->fpath, date('r') . " Get option ({$id})n", FILE_APPEND);     if (!count($this->fields))      $this->load_opts();     if (isset($this->fields[$id]))    {      if ($this->debug)        file_put_contents($this->fpath, date('r') . " Value: {$this->fields[$id]}n", FILE_APPEND);      return $this->fields[$id];    }     if ($this->debug)      file_put_contents($this->fpath, date('r') . " Option not foundn", FILE_APPEND);     return null;  }   function load_opts()  {    if ($this->debug)      file_put_contents($this->fpath, date('r') . " Load optionsn", FILE_APPEND);     $this->db->sql('SELECT * FROM config ORDER BY `name` ASC');    $results = $this->db->select();     for ($i = 0; $i < count($results); $i++)    {      $this->fields[$results[$i]['name']] = $results[$i]['val'];      $this->db_keys[] = $results[$i]['name'];    }     if ($this->debug)      file_put_contents($this->fpath, date('r') . " Options loaded:n" . print_r($this->fields, true), FILE_APPEND);  }   function set_opt($id, $val)  {    if ($this->debug)      file_put_contents($this->fpath, date('r') . " Set option ({$id}, {$val})n", FILE_APPEND);     if (!count($this->fields))      $this->load_opts();     $this->fields[$id] = $val;    $this->dirty[$id] = true;  }}
  • Like 2
Link to comment
Share on other sites

 

Right, when you create a new object, e.g.:

 

$db = new mysqli();

 

then the class constructor gets executed once the new object instance gets created. The most common thing that constructors are used for is probably to initialize various non-constant properties of the object. Like the manual for properties says:

 

 

 

 

Look at example 1 on that page to see examples of invalid and valid property declarations. If your class has properties that need to be initialized to non-constant values, you do that in the constructor.

 

Often creating an object also involves passing arguments when you create the object, e.g.:

 

$db = new mysqli($host, $username, $password, $database);

 

You're passing 4 arguments to the constructor, so the constructor needs to save or use those values.

 

http://www.php.net/manual/en/mysqli.construct.php

 

 

 

No, classes in PHP can only have a single constructor. You might have a class that extends or inherits from other classes or interfaces, and each of those can have their own constructor, but a single class wouldn't have more than one. Other languages allow different kinds of constructors, for example a copy constructor that would get executed if you created a copy of the object.

 

The class can also have a destructor that gets executed when the object gets destroyed if you need to do anything to clean up. Destructors aren't used a whole lot, one time I can think of having used a destructor was for a class that manages the configuration options for an application. When you create the class you can do things like get the current value of an option or change the value. Instead of updating the database immediately whenever you change a value, I had it keeping track of which values got changed and then the destructor checked for that and updated the database if anything was changed during the script. Here's an example:

<?php class app_config{  private $fields;  private $dirty;  private $db;  private $debug;  private $fpath;  private $db_keys;   function __construct()  {    global $db;    /*    Why it is necessary to keep a reference to global db:       This class uses the db object in the destructor.  There is no guarantee      which order objects will get destroyed in.  An object will not get destroyed      if there are references to it somewhere else.  Storing a reference to the      global db object in this class ensures that this object will be available      for the destructor to use.       A side-effect of this is that this class requires the db object to have      already been created when an object of this class is instantiated.    */     $this->debug = false;    $this->fpath = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'config.log';     $this->fields = array();    $this->dirty = array();    $this->db_keys = array();    $this->db = $db;     if ($this->debug)      file_put_contents($this->fpath, date('r') . " Config class createdn", FILE_APPEND);  }   function __destruct()  {    # commit changes    $tmp = array();    foreach ($this->dirty as $k => $v)    {      $tmp[] = $k;      $update = array('val' => $this->fields[$k]);      if (in_array($k, $this->db_keys))        $this->db->update('config', $update, "`name`='{$k}'");      else        $this->db->insert('config', array('name' => $k, 'val' => $this->fields[$k]));    }    if ($this->debug)      file_put_contents($this->fpath, date('r') . " Config class destroyed.  Updates:n" . print_r($tmp, true), FILE_APPEND);  }   function get_opt($id)  {    if ($this->debug)      file_put_contents($this->fpath, date('r') . " Get option ({$id})n", FILE_APPEND);     if (!count($this->fields))      $this->load_opts();     if (isset($this->fields[$id]))    {      if ($this->debug)        file_put_contents($this->fpath, date('r') . " Value: {$this->fields[$id]}n", FILE_APPEND);      return $this->fields[$id];    }     if ($this->debug)      file_put_contents($this->fpath, date('r') . " Option not foundn", FILE_APPEND);     return null;  }   function load_opts()  {    if ($this->debug)      file_put_contents($this->fpath, date('r') . " Load optionsn", FILE_APPEND);     $this->db->sql('SELECT * FROM config ORDER BY `name` ASC');    $results = $this->db->select();     for ($i = 0; $i < count($results); $i++)    {      $this->fields[$results[$i]['name']] = $results[$i]['val'];      $this->db_keys[] = $results[$i]['name'];    }     if ($this->debug)      file_put_contents($this->fpath, date('r') . " Options loaded:n" . print_r($this->fields, true), FILE_APPEND);  }   function set_opt($id, $val)  {    if ($this->debug)      file_put_contents($this->fpath, date('r') . " Set option ({$id}, {$val})n", FILE_APPEND);     if (!count($this->fields))      $this->load_opts();     $this->fields[$id] = $val;    $this->dirty[$id] = true;  }}

wow thank you sir.. that's just the kind of answer i was looking for.. thank you very much!

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...