Using print_r and var_dump with circular reference

Christian Davén picture Christian Davén · Jun 9, 2011 · Viewed 21.1k times · Source

I'm using the MVC framework Symfony, and it seems a lot of the built-in objects I want to debug have circular references. This makes it impossible to print the variables with print_r() or var_dump() (since they follow circular references ad infinitum or until the process runs out of memory, whichever comes first).

Instead of writing my own print_r clone with some intelligence, are there better alternatives out there? I only want to be able to print a variable (object, array or scalar), either to a log file, http header or the web page itself.

Edit: to clarify what the problem is, try this code:

<?php

class A
{
    public $b;
    public $c;

    public function __construct()
    {
        $this->b = new B();
        $this->c = new C();
    }
}

class B
{
    public $a;

    public function __construct()
    {
        $this->a = new A();
    }
}

class C
{
}

ini_set('memory_limit', '128M');
set_time_limit(5);

print_r(new A());
#var_dump(new A());
#var_export(new A());

It doesn't work with print_r(), var_dump() or var_export(). The error message is:

PHP Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 523800 bytes) in print_r_test.php on line 10

Answer

Alorian picture Alorian · Jun 4, 2013

Doctrine have the same service class.

Example of usage:

<?php echo "<pre>"; \Doctrine\Common\Util\Debug::dump($result, 4); echo "</pre>";?>