35
loading...
This website collects cookies to deliver better user experience
Just the Gist
A simple way of debugging is to use the built-in PHP function var_dump() to print out the contents of a variable. But it's not the only way to do it. Here's a short introduction to the basics of debugging in PHP.
var_dump()
, var_export()
and print_r()
are some of the functions you can use to do that. They do their work in slightly different manners:function | input | output | return value |
---|---|---|---|
var_dump |
"1.1" |
string(3) "1.1" |
no |
var_dump |
1.1 |
float(1.1) |
no |
var_export |
"1.1" |
'1.1' |
optional |
var_export |
1.1 |
1.1 |
optional |
print_r |
"1.1" |
1.1 |
optional |
print_r |
1.1 |
1.1 |
optional |
var_export
or print_r
if you want to store the output of the function somewhere, as it lacks a return value.debug_backtrace()
is yet another function for debugging your code. It will get you a code trace of how you ended where you are. Here's an example of a simple "Hello Mark"-program:<?php
function hello(string $name)
{
$greeting = "Hello";
if ($name != "Mark") {
var_dump(debug_backtrace());
return "";
}
return $greeting;
}
function sayHello()
{
echo hello("Bark");
}
sayHello();
array(2) {
[0]=>
array(4) {
["file"]=>
string(54) "path\to\file\example.php"
["line"]=>
int(15)
["function"]=>
string(5) "hello"
["args"]=>
array(1) {
[0]=>
string(4) "Bark"
}
}
[1]=>
array(4) {
["file"]=>
string(54) "path\to\file\example.php"
["line"]=>
int(18)
["function"]=>
string(8) "sayHello"
["args"]=>
array(0) {
}
}
}
hello
was called with the argument "Bark" from line 15 in our code. That means that the function was called from the function sayHello
, which in turn was called from line 18. We got this trace because we had added the debug_backtrace()
to show how we ended up trying to greet someone not named "Mark".echo
statements instead? Is there a better way to debug the code, and how would you go about doing that? Comment below and let us know what you think ✍debug_backtrace
: https://www.php.net/manual/en/function.debug-backtrace.php