Jump to content

DarnJhud

Members
  • Posts

    7
  • Joined

  • Last visited

Posts posted by DarnJhud

  1.  

    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!

  2. 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 :)

  3. 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??

  4. Hi, I'm just new to web programming and and I want to learn which code is which.

    what command is used to edit my web content without saving it in the database?

     

    I've been experimenting on facebook and tried to edit my "about me" page and when i view it on page source, i noticed that it is not saved on database.

     

    asd.png

     

    so for example i have a simple page containing this:

     

    <body>

    <div> Content edit me</div>

    </body>

     

    how can i edit the content of this div?

     

    will this need a bit of php or just a plain html5 can do this thing??

  5. sir i have one question. when using WAMP server, every time i create PHP file it should be located on www folder created by WAMP upon install? because when i try to copy my PHP file into my FTP server folder i cant view them.

  6. hi everyone, i am in my 3rd year college and i want to learn the PHP programming language. i have a background on other programming languages like HTML, JavaScript, JAVA and Visual Basic which i study both in school and via online. and when i come to research on PHP i have learned that it is need to be configured on my web server?and so i search for more article and i found this site on how to check if my web server supports PHP. 1st it make me do a simple info.php (containing this code: <?php phpinfo(); ?> ) -- the result is blank. just a white page, no error. nothing.. 2nd is making another .php file containing this code:

    <?php// Start Sessionsession_start();// Show bannerecho '<b>Session Support Checker</b><hr />';// Check if the page has been reloadedif(!isset($_GET['reload']) OR $_GET['reload'] != 'true') {   // Set the message   $_SESSION['MESSAGE'] = 'Session support enabled!<br />';   // Give user link to check   echo '<a href="?reload=true">Click HERE</a> to check for PHP Session Support.<br />';} else {   // Check if the message has been carried on in the reload   if(isset($_SESSION['MESSAGE'])) {	  echo $_SESSION['MESSAGE'];   } else {	  echo 'Sorry, it appears session support is not enabled, or you PHP version is to old. <a href="?reload=false">Click HERE</a> to go back.<br />';   }}?>

    and the result is this asdasd.png (i used FTP client (FileZilla Server) to upload those file. and i open them using my browser.) does this mean that my web server dont support PHP? if not what should i do to make my web server support PHP?

    • Like 1
×
×
  • Create New...