Var_dump () without show protected and private property

Are there any functions or as a var_dump () object without showing its 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" 
+4
source share
4 answers

As this page shows, you can simply iterate over an 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"; } ?> 

Please note that the $ Password variable is not visible anywhere, because it is allocated by Private, and we are trying to access it from the global scope.

If you want to create your own var dump, you can do it like this:

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

The reason this happens is that when you access an object outside of you, you have access to its public member variables.

+3
source

json_encode will encode only public properties.

+7
source

What about json_decode(json_encode($obj)) ?

0
source

One option is to use the __clone method in your class. There you can disable any unwanted properties from the clone of the object instance, for example:

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

then your var_dump will refer to the clone:

 var_dump( clone My_Object_Instance ); 

Or, if you need to clone elsewhere, your class can use the __debugInfo () method to fully control its var_dump output, for example, return get_object_vars ($ this) after you disconnect any unwanted array elements.

0
source

Source: https://habr.com/ru/post/1432809/


All Articles