Christian Davén Christian Davén -4 years ago 150
PHP Question

Using print_r and var_dump with circular reference

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 Source

We are using the PRADO Framework and it has a built in class called "TVarDumper" which can handle such complex objects pretty well - it even can format it in nice HTML incl. Syntax Highlighting. You can get that class from HERE.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download