Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing private properties of object

Tags:

oop

php

Tried and searched this but never seemed to find it here in SO tried using unset($this->property_name) but it still shows up when I use a print_r($object_name), is it impossible to remove a private property of an object?

here's a sample code

class my_obj
{
    private $a, $b, $c, $d;
    public function __construct($data = null)
    {
        if($data)
        {
            foreach($data as $key)
            {
                if(property_exists($this,$key))
                {
                    $this->$key = $value;
                }
            }
        }
    }

implementation:

$test = new my_obj(array('a'=>a, 'c'=>'c'));
echo '<pre>',print_r($test,TRUE),'</pre>';

the output would be something like this

my_obj Object
(
    [a:my_obje:private] => a
    [b:my_obje:private] => 
    [c:my_obje:private] => c
    [d:my_obje:private] => 
)

now i want those properties that are not set to be entirely removed again i tried unset and it doesnt seem to work

thanks for all that cared to answer this

like image 552
ianace Avatar asked Aug 12 '11 10:08

ianace


1 Answers

Aside from the fact that there's got be a better way to do you whatever it is that you need this for (you should explain the problem you need to solve in another question so that we can help you find a better solution), you can indeed remove private property as long as you do it in a context where you can access them.

class test
{
  private $prop = 'test';

  public function deleteProp()
  {
    unset($this->prop);
  }
}

$var = new test();
var_dump($var); // object(test)#1 (1) {["prop":"test":private] => string(4) "test"}
$var->deleteProp();
var_dump($var); // object(test)#1 (0) { }
like image 195
Lepidosteus Avatar answered Oct 11 '22 06:10

Lepidosteus