var_dump() without show protected and private property

邮差的信 提交于 2021-02-19 02:37:19

问题


Is there any functions or how to var_dump() object without showing it protected and private property?

example:

class foo {
    public $public = 'public';
    protected $protected = 'protected';
    private $private = 'private';
}

$Foo = new foo;
var_dump($Foo);
// Expected output "(string) public"

回答1:


As this page shows, you can just loop over the object:

<?php
    class person {
        public $FirstName = "Bill";
        public $MiddleName = "Terence";
        public $LastName = "Murphy";
        private $Password = "Poppy";
        public $Age = 29;
        public $HomeTown = "Edinburgh";
        public $FavouriteColour = "Purple";
    }

    $bill = new person();

    foreach($bill as $var => $value) {
        echo "$var is $value\n";
    }
?>

Note that the $Password variable is nowhere in sight, because it is marked Private and we're trying to access it from the global scope.

If you want to make your own var dump, you can do it as so:

function dumpObj( $obj )
{
    foreach( $obj as $k=>$v )
    {
        echo $k . ' : ' . $v ."\n";
    }
}

dumpObj( new WhateverClass() );

The reason this works is because when you access the object outside of itself, you only have access to its public facing member variables.




回答2:


json_encode will only encode public properties.




回答3:


How's about json_decode(json_encode($obj))?




回答4:


One option is to use the __clone method in your class. There you can unset any undesired properties from the clone of your object instance, e.g.:

public function __clone() {
    unset( $this->my_secret_property ); 
}

then your var_dump would reference the clone:

var_dump( clone My_Object_Instance );

Or, if you need your cloning elsewhere, your class can use the __debugInfo() method to completely control its var_dump output, such as returning get_object_vars( $this ), after you unset any unwanted array elements.



来源:https://stackoverflow.com/questions/12307790/var-dump-without-show-protected-and-private-property

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