www.webdeveloper.com
Results 1 to 5 of 5

Thread: Clear all object variables

  1. #1
    Join Date
    Aug 2006
    Posts
    23

    Clear all object variables

    I have a class and I would like to create a function to clear all variables within the object, regardless of how many variables are added or taken out. Something like this..

    class object()
    {
    $a;
    $b;
    $c;

    function clear_data()
    {
    foreach(variable in this object)
    variable = null;
    }
    }

    Is there a built in PHP function to handle this?

  2. #2
    Join Date
    Nov 2008
    Posts
    2,477
    PHP Code:
    foreach($object as $property => $value)  {  
        unset(
    $object->$propery);  

    ... though surely it would be easier to just create a new object?

  3. #3
    Join Date
    Aug 2006
    Posts
    23
    Don't think that was quite what I was looking for. The reason I was looking for a way to clear all variables in an object is this. The object has a function called load, that just loads a bunch of data from the DB. If while loading, it finds a bad piece of data, I want it to clear all the variables within the object.

    I could make a function called clear() and just have it do something like:

    $this->a = null;
    $this->b = null;
    $this->c = null;

    The problem is, I want this class to be inherited, so that any child class can use this method and it will work.

  4. #4
    Join Date
    Aug 2004
    Location
    Ankh-Morpork
    Posts
    19,175
    Something like this?
    PHP Code:
    <?php
    class Foo
    {
       public 
    $a;
       public 
    $b;
       public function 
    clearAllVars()
       {
          
    $vars get_object_vars($this);
          foreach(
    $vars as $key => $val)
          {
             
    $this->$key null;
          }
       }
    }

    // TEST:
    ?>
    <pre><?php
    $foo 
    = new Foo();
    $foo->'a';
    $foo->'b';
    $foo->'c'// create new object variable
    var_dump($foo);
    $foo->clearAllVars();
    var_dump($foo);
    ?></pre>
    Output:
    Code:
    object(Foo)#1 (3) {
      ["a"]=>
      string(1) "a"
      ["b"]=>
      string(1) "b"
      ["c"]=>
      string(1) "c"
    }
    object(Foo)#1 (3) {
      ["a"]=>
      NULL
      ["b"]=>
      NULL
      ["c"]=>
      NULL
    }
    "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

  5. #5
    Join Date
    Aug 2006
    Posts
    23
    Ah, perfect. Thank you very much.

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