开发者

Removing private properties of object

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)
    {
开发者_如何学C        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


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) { }


If you don't mind creating a new object, you could use PHP's built-in get_object_vars():

$public_properties = get_object_vars($object); // get only the public properties of the object
$public_properties = (object)$public_properties; // turn array back into object

For more information, see http://php.net/manual/function.get-object-vars.php

edited: corrected typo

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜