Debugging with PHP. Now, what should I do...?
table of contents
Hello.
My name is Bandai and I am in charge of Wild on the development team.
Debugging is a must when proceeding with development. This time, I would like to explain about var_export, which is a powerful ally when debugging.
How do you go about debugging?
I think the basic of the basics is var_dump. If you don't know this, you've probably never written PHP.
However, var_dump cannot be output to the log (by itself. Although it is not impossible, it is not convenient at all when considering debugging purposes).
I think this is the biggest problem with var_dump.
So, is it print_r?
Echoing the pre tag before and after print_r is such a joke that it's no longer a joke. I do it sometimes (do I do it?).
serialize? Do you want to put it into the DB? If it's a PHP premise, that's fine...it doesn't make any sense. Debugging with serialize may seem like a thorny path, but it happens sometimes.
If you want to display everything, you can use var_dump, but if you want to use it for things like writing to logs, I recommend var_export.
Maybe it's not enough to say it out loud now.
What is var_export?
As the name suggests, the var_export function is used to export variables.
As proof of this, the output information is exactly the same as PHP variable declarations.
<?php $hoge = array( 'a', 'b', 'c', 'd', ); var_export($hoge);
The output looks like this:
array ( 0 => 'a', 1 => 'b', 2 => 'c', 3 => 'd', )
By the way, the formats of var_dump and print_r are as follows.
// var_dump array(4) { [0]=> string(1) "a" [1]=> string(1) "b" [2]=> string(1) "c" [3]=> string (1) "d" } // print_r Array ( [0] => a [1] => b [2] => c [3] => d )
By the way, the sample source of
PHP: var_export - Manual describes how to redefine var_exported data as a variable using eval, but I'm not sure how to use it, but that's the gist.
The true power of var_export
var_export fully demonstrates its capabilities in API development, which is our specialty.
In API development, we often process received requests and output them in JSON format, but when we use var_dump, JSON data with var_dumped information is returned as a response, so when parsing JSON on the client side, It will definitely be an error.
At that time, I think you often check the operation by tailing the log file, but as mentioned above, you need a little trick to write down the var_dump information to the log file.
With var_export, you can store the output in a variable just by adding true to the second argument, so outputting to the log file is very easy.
With fuelphp, you can output to a log file as follows.
$hoge = array( 'a', 'b', 'c', 'd', ); Log::debug(var_export($hoge, true));
This is a feat that var_dump with variable arguments simply cannot do.
var_dump is useful because it also outputs the number of data items in the array.
All I can say is get used to it.
That's it.