/    Sign up×
Community /Pin to ProfileBookmark

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?

to post a comment
PHP

4 Comments(s)

Copy linkTweet thisAlerts:
@MindzaiJul 23.2009 — [code=php]foreach($object as $property => $value) {

unset($object->$propery);

}[/code]


... though surely it would be easier to just create a new object?
Copy linkTweet thisAlerts:
@BengaltgrsauthorJul 23.2009 — 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.
Copy linkTweet thisAlerts:
@NogDogJul 24.2009 — Something like this?
[code=php]
<?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 = 'a';
$foo->b = 'b';
$foo->c = 'c'; // create new object variable
var_dump($foo);
$foo->clearAllVars();
var_dump($foo);
?></pre>
[/code]

Output:
object(Foo)#1 (3) {
["a"]=&gt;
string(1) "a"
["b"]=&gt;
string(1) "b"
["c"]=&gt;
string(1) "c"
}
object(Foo)#1 (3) {
["a"]=&gt;
NULL
["b"]=&gt;
NULL
["c"]=&gt;
NULL
}
Copy linkTweet thisAlerts:
@BengaltgrsauthorJul 24.2009 — Ah, perfect. Thank you very much.
×

Success!

Help @Bengaltgrs spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.19,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...