Why use __debugInfo()?

Asked

Viewed 153 times

5

I saw that PHP 5.6 has now created the new magic method called __debugInfo.

This method aims to return a array, which will be printed in the var_dump. That one array returned obviously must offer information for debug class.

I would like to understand in which cases this would be useful?

The var_dump traditional in itself was no longer enough? Was this done only to solve circular reference problems?

1 answer

4


When we use the var_dump without the method __debugInfo will be displayed at the output the data, including the private and protected variables, as cited in the documentation:

This method is called by var_dump() when dumping an Object to get the properties that should be Shown. If the method isn’t defined on an Object, then all public, protected and private properties will be Shown.

Then the __debugInfo will be used to limit what will be displayed on output, an example:

<?php
class Foo
{
    private $podeIrParaoLog = 'Olá';
    private $naoPodeIrParaoLog = 'Informação sensivel';

    public function __debugInfo()
    {
        return [
            'private::podeIrParaoLog' => $this->podeIrParaoLog,
        ];
    }
}

$foo = new Foo();

var_dump($foo);

print_r($foo);

The way out will be something like:

object(Foo)#1 (1) {
  ["private::podeIrParaoLog"]=>
  string(4) "Olá"
}
Foo Object
(
    [private::podeIrParaoLog] => Olá
)
  • 1

    I cost understanding this method, in all my tests it doesn’t work. Even with your example it didn’t work.

  • 1

    @Boyprogrammer you are right, most people do blog posts or even answers in other places that are not as direct as they should be and another time they do the opposite, are too direct when they should be more detailed before presenting the code part, explaining necessary technical concepts. One of the reasons I strive to formulate long and other short answers is to analyze when one type and when another is necessary, because I also penetrated to learn because of bad texts that I found on the Internet, so I try to do better to help.

  • 1

    That’s why I tested positive, I can tell you know what you’re talking about and you know what you’re saying. But thank you for the answer, now that I saw that it is very old. But it was good for study. Thank you

Browser other questions tagged

You are not signed in. Login or sign up in order to post.