Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

var_dump() without show protected and private property

Tags:

php

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"
like image 321
GusDeCooL Avatar asked Dec 27 '22 18:12

GusDeCooL


2 Answers

json_encode will only encode public properties.

like image 52
Explosion Pills Avatar answered Jan 08 '23 05:01

Explosion Pills


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.

like image 44
Josh Avatar answered Jan 08 '23 04:01

Josh