The VarDumper Component

The VarDumper component provides mechanisms for extracting the state out ofany PHP variables. Built on top, it provides a better dump() functionthat you can use instead of var_dump.

Installation

  1. $ composer require --dev symfony/var-dumper

Note

If you install this component outside of a Symfony application, you mustrequire the vendor/autoload.php file in your code to enable the classautoloading mechanism provided by Composer. Readthis article for more details.

Note

If using it inside a Symfony application, make sure that the DebugBundle hasbeen installed (or run composer require —dev symfony/debug-bundle to install it).

The dump() Function

The VarDumper component creates a global dump() function that you canuse instead of e.g. var_dump. By using it, you'll gain:

  • Per object and resource types specialized view to e.g. filter outDoctrine internals while dumping a single proxy entity, or get moreinsight on opened files with stream_get_meta_data;
  • Configurable output formats: HTML or colored command line output;
  • Ability to dump internal references, either soft ones (objects orresources) or hard ones (=& on arrays or objects properties).Repeated occurrences of the same object/array/resource won't appearagain and again anymore. Moreover, you'll be able to inspect thereference structure of your data;
  • Ability to operate in the context of an output buffering handler.For example:
  1. require __DIR__.'/vendor/autoload.php';
  2.  
  3. // create a variable, which could be anything!
  4. $someVar = ...;
  5.  
  6. dump($someVar);
  7.  
  8. // dump() returns the passed value, so you can dump an object and keep using it
  9. dump($someObject)->someMethod();

By default, the output format and destination are selected based on yourcurrent PHP SAPI:

  • On the command line (CLI SAPI), the output is written on STDOUT. Thiscan be surprising to some because this bypasses PHP's output bufferingmechanism;
  • On other SAPIs, dumps are written as HTML in the regular output.

Tip

You can also select the output format explicitly defining theVAR_DUMPER_FORMAT environment variable and setting its value to eitherhtml or cli.

Note

If you want to catch the dump output as a string, please read theadvanced documentation which contains examples of it.You'll also learn how to change the format or redirect the output towherever you want.

Tip

In order to have the dump() function always available when runningany PHP code, you can install it globally on your computer:

  • Run composer global require symfony/var-dumper;
  • Add auto_prepend_file = ${HOME}/.composer/vendor/autoload.phpto your php.ini file;
  • From time to time, run composer global update symfony/var-dumperto have the latest bug fixes.

Tip

The VarDumper component also provides a dd() ("dump and die") helperfunction. This function dumps the variables using dump() andimmediately ends the execution of the script (using exit).

The Dump Server

The dump() function outputs its contents in the same browser window orconsole terminal as your own application. Sometimes mixing the real outputwith the debug output can be confusing. That's why this component provides aserver to collect all the dumped data.

Start the server with the server:dump command and whenever you call todump(), the dumped data won't be displayed in the output but sent to thatserver, which outputs it to its own console or to an HTML file:

  1. # displays the dumped data in the console:
  2. $ php bin/console server:dump
  3. [OK] Server listening on tcp://0.0.0.0:9912
  4.  
  5. # stores the dumped data in a file using the HTML format:
  6. $ php bin/console server:dump --format=html > dump.html

Inside a Symfony application, the output of the dump server is configured withthe dump_destination option of thedebug package:

  • YAML
  1. # config/packages/debug.yaml
  2. debug:
  3. dump_destination: "tcp://%env(VAR_DUMPER_SERVER)%"
  • XML
  1. <!-- config/packages/debug.xml -->
  2. <?xml version="1.0" encoding="UTF-8" ?>
  3. <container xmlns="http://symfony.com/schema/dic/debug"
  4. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  5. xmlns:debug="http://symfony.com/schema/dic/debug"
  6. xsi:schemaLocation="http://symfony.com/schema/dic/services
  7. https://symfony.com/schema/dic/services/services-1.0.xsd
  8. http://symfony.com/schema/dic/debug https://symfony.com/schema/dic/debug/debug-1.0.xsd">
  9.  
  10. <debug:config dump-destination="tcp://%env(VAR_DUMPER_SERVER)%"/>
  11. </container>
  • PHP
  1. // config/packages/debug.php
  2. $container->loadFromExtension('debug', [
  3. 'dump_destination' => 'tcp://%env(VAR_DUMPER_SERVER)%',
  4. ]);

Outside a Symfony application, use the ServerDumper class:

  1. require __DIR__.'/vendor/autoload.php';
  2.  
  3. use Symfony\Component\VarDumper\Cloner\VarCloner;
  4. use Symfony\Component\VarDumper\Dumper\CliDumper;
  5. use Symfony\Component\VarDumper\Dumper\ContextProvider\CliContextProvider;
  6. use Symfony\Component\VarDumper\Dumper\ContextProvider\SourceContextProvider;
  7. use Symfony\Component\VarDumper\Dumper\HtmlDumper;
  8. use Symfony\Component\VarDumper\Dumper\ServerDumper;
  9. use Symfony\Component\VarDumper\VarDumper;
  10.  
  11. $cloner = new VarCloner();
  12. $fallbackDumper = \in_array(\PHP_SAPI, ['cli', 'phpdbg']) ? new CliDumper() : new HtmlDumper();
  13. $dumper = new ServerDumper('tcp://127.0.0.1:9912', $fallbackDumper, [
  14. 'cli' => new CliContextProvider(),
  15. 'source' => new SourceContextProvider(),
  16. ]);
  17.  
  18. VarDumper::setHandler(function ($var) use ($cloner, $dumper) {
  19. $dumper->dump($cloner->cloneVar($var));
  20. });

Note

The second argument of ServerDumperis a DataDumperInterface instanceused as a fallback when the server is unreachable. The third argument are thecontext providers, which allow to gather some info about the context in which thedata was dumped. The built-in context providers are: cli, request and source.

Then you can use the following command to start a server out-of-the-box:

  1. $ ./vendor/bin/var-dump-server
  2. [OK] Server listening on tcp://127.0.0.1:9912

DebugBundle and Twig Integration

The DebugBundle allows greater integration of this component into Symfonyapplications.

Since generating (even debug) output in the controller or in the modelof your application may just break it by e.g. sending HTTP headers orcorrupting your view, the bundle configures the dump() function so thatvariables are dumped in the web debug toolbar.

But if the toolbar cannot be displayed because you e.g. calleddie()/exit()/dd() or a fatal error occurred, then dumps are writtenon the regular output.

In a Twig template, two constructs are available for dumping a variable.Choosing between both is mostly a matter of personal taste, still:

  • {% dump foo.bar %} is the way to go when the original template outputshall not be modified: variables are not dumped inline, but in the webdebug toolbar;
  • on the contrary, {{ dump(foo.bar) }} dumps inline and thus may or notbe suited to your use case (e.g. you shouldn't use it in an HTMLattribute or a <script> tag).This behavior can be changed by configuring the debug.dumpdestinationoption. Read more about this and other options in[_the DebugBundle configuration reference](https://symfony.com/doc/current/reference/configuration/debug.html).

Tip

If the dumped contents are complex, consider using the local search box tolook for specific variables or values. First, click anywhere on the dumpedcontents and then press Ctrl. + F or Cmd. + F to make the localsearch box appear. All the common shortcuts to navigate the search resultsare supported (Ctrl. + G or Cmd. + G, F3, etc.) Whenfinished, press Esc. to hide the box again.

Using the VarDumper Component in your PHPUnit Test Suite

The VarDumper component providesa traitthat can help writing some of your tests for PHPUnit.

This will provide you with two new assertions:

  • assertDumpEquals()
  • verifies that the dump of the variable given as the second argument matchesthe expected dump provided as the first argument.
  • assertDumpMatchesFormat()
  • is like the previous method but accepts placeholders in the expected dump,based on the assertStringMatchesFormat() method provided by PHPUnit.Example:
  1. use PHPUnit\Framework\TestCase;
  2. use Symfony\Component\VarDumper\Test\VarDumperTestTrait;
  3.  
  4. class ExampleTest extends TestCase
  5. {
  6. use VarDumperTestTrait;
  7.  
  8. public function testWithDumpEquals()
  9. {
  10. $testedVar = [123, 'foo'];
  11.  
  12. $expectedDump = <<<EOTXT
  13. array:2 [
  14. 0 => 123
  15. 1 => "foo"
  16. ]
  17. EOTXT;
  18.  
  19. // if the first argument is a string, it must be the whole expected dump
  20. $this->assertDumpEquals($expectedDump, $testedVar);
  21.  
  22. // if the first argument is not a string, assertDumpEquals() dumps it
  23. // and compares it with the dump of the second argument
  24. $this->assertDumpEquals($testedVar, $testedVar);
  25. }
  26. }

Dump Examples and Output

For simple variables, reading the output should be straightforward.Here are some examples showing first a variable defined in PHP,then its dump representation:

  1. $var = [
  2. 'a simple string' => "in an array of 5 elements",
  3. 'a float' => 1.0,
  4. 'an integer' => 1,
  5. 'a boolean' => true,
  6. 'an empty array' => [],
  7. ];
  8. dump($var);

../_images/01-simple.png

Note

The gray arrow is a toggle button for hiding/showing children ofnested structures.

  1. $var = "This is a multi-line string.\n";
  2. $var .= "Hovering a string shows its length.\n";
  3. $var .= "The length of UTF-8 strings is counted in terms of UTF-8 characters.\n";
  4. $var .= "Non-UTF-8 strings length are counted in octet size.\n";
  5. $var .= "Because of this `\xE9` octet (\\xE9),\n";
  6. $var .= "this string is not UTF-8 valid, thus the `b` prefix.\n";
  7. dump($var);

../_images/02-multi-line-str.png

  1. class PropertyExample
  2. {
  3. public $publicProperty = 'The `+` prefix denotes public properties,';
  4. protected $protectedProperty = '`#` protected ones and `-` private ones.';
  5. private $privateProperty = 'Hovering a property shows a reminder.';
  6. }
  7.  
  8. $var = new PropertyExample();
  9. dump($var);

../_images/03-object.png

Note

#14 is the internal object handle. It allows comparing twoconsecutive dumps of the same object.

  1. class DynamicPropertyExample
  2. {
  3. public $declaredProperty = 'This property is declared in the class definition';
  4. }
  5.  
  6. $var = new DynamicPropertyExample();
  7. $var->undeclaredProperty = 'Runtime added dynamic properties have `"` around their name.';
  8. dump($var);

../_images/04-dynamic-property.png

  1. class ReferenceExample
  2. {
  3. public $info = "Circular and sibling references are displayed as `#number`.\nHovering them highlights all instances in the same dump.\n";
  4. }
  5. $var = new ReferenceExample();
  6. $var->aCircularReference = $var;
  7. dump($var);

../_images/05-soft-ref.png

  1. $var = new \ErrorException(
  2. "For some objects, properties have special values\n"
  3. ."that are best represented as constants, like\n"
  4. ."`severity` below. Hovering displays the value (`2`).\n",
  5. 0,
  6. E_WARNING
  7. );
  8. dump($var);

../_images/06-constants.png

  1. $var = [];
  2. $var[0] = 1;
  3. $var[1] =& $var[0];
  4. $var[1] += 1;
  5. $var[2] = ["Hard references (circular or sibling)"];
  6. $var[3] =& $var[2];
  7. $var[3][] = "are dumped using `&number` prefixes.";
  8. dump($var);

../_images/07-hard-ref.png

  1. $var = new \ArrayObject();
  2. $var[] = "Some resources and special objects like the current";
  3. $var[] = "one are sometimes best represented using virtual";
  4. $var[] = "properties that describe their internal state.";
  5. dump($var);

../_images/08-virtual-property.png

  1. $var = new AcmeController(
  2. "When a dump goes over its maximum items limit,\n"
  3. ."or when some special objects are encountered,\n"
  4. ."children can be replaced by an ellipsis and\n"
  5. ."optionally followed by a number that says how\n"
  6. ."many have been removed; `9` in this case.\n"
  7. );
  8. dump($var);

../_images/09-cut.png

Learn More