One of the most common ways to debug an error in PHP ecosystem is to dump the variable on the screen, and figure out what is going wrong with it.
The most common way we do it in PHP is via using var_dump
function.
var_dump function dumps all the information about the variable or object on your page, but it does not stop the execution of the program further.
Let’s consider an example where if you have an associate array and you want to dump it on the screen.
<?php
$prices = [
'🍔' => 5.99,
'🍟' => 4,
'🍻' => 10
];
var_dump($prices);
This is what you get on the screen.
As you can see our code did not die and also the formatting very nice 🤔
Using dd in PHP
If you are a laravel developer you must be aware of dd() function, dd dumps and die. There is no dd function in php if you try to do dd($prices) in the above example it will throw an error Call to undefined function dd()
.
We can however create our own dd function, that will dump the variable/object and then die the script execution.
We have created a new dd
function, and wrapped the var_dump
around pre
tags so that it gives out a nice formatting in the browser and a more readable dump.
<?php
function dd($data) {
echo '<pre>';
var_dump($data);
echo '</pre>';
die;
}
$prices = [
'🍔' => 100,
'🍟' => 10,
'🍻' => 4
];
dd($prices);
This is how you see the output, and the php scripts die after dumping. It does not execute the further code.
You can isolate this function in a reusable functions file or a Class.
I hope you enjoyed the read!
Feel free to follow me on GitHub, LinkedIn and DEV for more!
Top comments (1)
A very handy thing!
I would suggest two things: