tonix
tonix

Reputation: 6939

Why does var_dump(debug_backtrace()) within a method triggers object's __debugInfo()?

Could someone explain me why in the following case:

class A {

    public function methodA() {
        var_dump(debug_backtrace());
    }

    public function __debugInfo() {
        return [];
    }

    public function __clone() {
        echo "clone A!!!";
    }

}

class B extends A {

    public function __clone() {
        echo "clone B!!!";
        $a = new A();
        clone $a;
    }

    public function __debugInfo() {
        echo __FUNCTION__ . '!!!';
        $a = new A();
        var_dump($a);
    }

}

When I create an object of type B and call methodA():

$b = new B();
$b->methodA();

I __debugInfo() is also executed:

array(1) {
  [0]=>
  array(7) {
    ["file"]=>
    string(14) "php shell code"
    ["line"]=>
    int(1)
    ["function"]=>
    string(7) "methodA"
    ["class"]=>
    string(1) "A"
    ["object"]=>
    __debugInfo!!!object(A)#2 (0) {
}
object(B)#1 (0) {
    }
    ["type"]=>
    string(2) "->"
    ["args"]=>
    array(0) {
    }
  }
}

I didn't dumped the object, I dumped the debug backtrace...

Is there something I am missing in the documentation? http://php.net/manual/en/language.oop5.magic.php#object.debuginfo

Thank you!

Upvotes: 1

Views: 407

Answers (1)

Tarun Kumar
Tarun Kumar

Reputation: 201

This is because, debug_backtrace() has option :

DEBUG_BACKTRACE_PROVIDE_OBJECT : true

which will internally dump the object with the trace.

Furthermore, __debugInfo() method is called by var_dump() when dumping an object to get the properties that should be shown.

__debugInfo() is one of the PHP magic methods.You cannot have functions with these names in any of your classes unless you want the magic functionality associated with them.

So, to avoid calling __debugInfo(), try :

public function methodA() {
    var_dump(debug_backtrace(0));
}

Upvotes: 3

Related Questions