Welcome Guest, Not a member yet? Register   Sign In
saving data via __destruct
#1

[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!
#2

[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
#3

[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?
#4

[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;
#5

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

[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 :-)




Theme © iAndrew 2016 - Forum software by © MyBB