Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Is it possible to hide a specific class fields from print_r ?

<?php

class DataManager {
    public $data = array();
}

class Data {
    public $manager;
    public $data = array();

    public function Data ($m, $d) {
        $this->manager = $m;
        $this->data = $d;
    }
}

$manager = new DataManager();

for ($a = 0; $a < 10; $a++) {
    $manager->data[] = new Data($manager, 'Test ' . md5($a));
}

echo '<pre>';
print_r($manager);

?>

This would print

DataManager Object ( [data] => Array ( [0] => Data Object ( [manager] => DataManager Object RECURSION [data] => Test cfcd208495d565ef66e7dff9f98764da )

        [1] => Data Object
            (
                [manager] => DataManager Object  *RECURSION*
                [data] => Test c4ca4238a0b923820dcc509a6f75849b
            )    .......

Is it possible to somehow change the output behavior so it print's like this? Like with DocComment /** @hidden **/

DataManager Object ( [data] => Array ( [0] => Data Object ( [data] => Test cfcd208495d565ef66e7dff9f98764da )

        [1] => Data Object
            (
                [data] => Test c4ca4238a0b923820dcc509a6f75849b
            )

If not, is there some sort of PHP lib that maybe uses Reflection and somehow bypasses stuff?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
434 views
Welcome To Ask or Share your Answers For Others

1 Answer

New Magic method __debugInfo() was introduced in PHP 5.6 that will allow you to modify the default behaviour of var_dump() when dumping your objects.

Have a look at the documentation.

Example:

<?php
class C {
    private $prop;

    public function __construct($val) {
        $this->prop = $val;
    }

    public function __debugInfo() {
        return [
            'propSquared' => $this->prop ** 2,
        ];
    }
}

var_dump(new C(42));
?>

Returns:

object(C)#1 (1) {
  ["propSquared"]=>
  int(1764)
}

Although this question is 4 years old, I'm sure someone will find this useful in the future.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...