A powerful function in the Laravel framework called dd() that enables programmers and developers to easily dump and check the contents of variables. The function's name, which stands for "dump and die," is frequently used in debugging and troubleshooting code.
The following is how they define it in their documentation: The dd function dumps the given variables and ends execution of the script.
In this post, we'll demonstrate how to create a similar function in pure PHP, which you can use in any project.
Creating the Function:
First, we need to check if the function already exists in the codebase. If it does not exist, we'll define our own version of the dd() function as seen below:
if (!function_exists('dd')) {
function dd(...$vars) {
// Get the current file and line
$backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 1);
$file = $backtrace[0]['file'];
$line = $backtrace[0]['line'];
// Output the current file and line
echo "<div style=' font-family: monospace; padding: 10px; background: black;color: white;'><div>
<div style='margin-bottom:10px'>
<span style='color: #04da04; font-weight: 600;'>File:</span> {$file}
</div>
<span style='color: #04da04; font-weight: 600;'> Line:</span> {$line}
</div>";
// Dump the variables using var_dump
foreach ($vars as $var) {
echo "<pre>";
var_dump($var);
echo "</pre>";
}
// Close the container div
echo "</div>";
// Exit the script
exit;
}
}
As depicted in the above code, this function will print the current file name, the current line where the function is located, and it takes an unlimited number of arguments.
Usage:
To use the function, simply call it anywhere in your code:
dd();
Output:
And the ouput will be like this:
This function is very useful for debugging and troubleshooting code, some example:
1- Check if you are working on the correct file.
2- Check if the (if statement is working to add the function if the condition is true).
3- Get the types of your variables or quires.
4- Check the contents of arrays, objects, queires, and API call to see what data is being passed around in your code.