Removing private properties of object

◇◆丶佛笑我妖孽 提交于 2021-02-09 04:22:41

问题


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


回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/7039045/removing-private-properties-of-object

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!