CodeIgniter Forums
saving data via __destruct - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forum-20.html)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forum-23.html)
+--- Thread: saving data via __destruct (/thread-25266.html)



saving data via __destruct - El Forum - 12-06-2009

[eluser]gino[/eluser]
Hi,

i'm still learning CI and not yet an expert in PHP Wink

i was just wondering if it's possible to save data into the database in the magic __destruct function?

example:

Code:
<?php

class Home extends Controller {

  private $mydata = array();

  public function __construct()
  {
    parent::Controller();
  }

  public function index()
  {
    $this->load->view('home');
    //data is added to the $this->mydata array
    //this could be done everywhere : views, models....
  }

  function __destruct()
  {
    $this->db->where('id', 1);
    $this->db->update('table', $this->mydata);
  }

}

i'm just not sure if this is a good thing todo!
and if the code will always be excecuted?!!

any experts please give me your thoughts.
thnx in advance!


saving data via __destruct - El Forum - 12-06-2009

[eluser]umefarooq[/eluser]
if you want to update you table every time when object is getting destroy then it is ok, please check the following link

http://php.net/manual/en/language.oop5.decon.php


saving data via __destruct - El Forum - 12-06-2009

[eluser]gino[/eluser]
thnx,
i already read the docs on php.net, but i'm just still a litle confused on when the destructor is actually called.

maybe a litle paranoid to! Smile
it's not possible that the CI->db object doesn't exist anymore?


saving data via __destruct - El Forum - 12-07-2009

[eluser]umefarooq[/eluser]
hi just try this simple class

Code:
<?

class test{
    private $obj_name;
    function __construct(){
        echo 'im constructer here<br />';
        $this->obj_name ='Hello im object<br />';
    }
    
    function name(){
        echo $this->obj_name;
    }
    
    function __destruct(){
        echo 'im destroying it.';
    }
    
}

$obj = new test();

$obj->name();

?&gt;



saving data via __destruct - El Forum - 12-07-2009

[eluser]Namaless[/eluser]
Use register_shutdown_function(array($this,"my_destruct_method")) ^_^


saving data via __destruct - El Forum - 12-07-2009

[eluser]gino[/eluser]
[quote author="Namaless" date="1260194298"]Use register_shutdown_function(array($this,"my_destruct_method")) ^_^[/quote]

thnx for the reply!
i'm currently looking into this method also Wink

@umefarooq
thnx for the example,
everything works as expected!

appreciated :-)