PHP built-in debugging function: var_dump() displays variable details, type, value, structure. print_r() prints information in a more readable format, suitable for debugging complex data structures. error_log() records messages to the error log to facilitate recording debugging information, errors or warnings.
How to use PHP built-in functions to debug code
PHP provides several built-in functions to help you debug code. These functions are simple to use but save a lot of time and effort.
var_dump()
var_dump()
The function displays information about a variable, including its type, value, and structure. This is useful for checking whether a variable contains an expected value or type.
$array = ['foo' => 'bar', 'baz' => 'qux']; var_dump($array);
Output:
array(2) { ["foo"]=> string(3) "bar" ["baz"]=> string(3) "qux" }
print_r()
print_r()
The function is similar to var_dump()
, but it prints the information in a more readable format. This is useful for debugging complex data structures.
$object = new stdClass(); $object->name = 'John Doe'; $object->age = 30; print_r($object);
Output:
stdClass Object ( [name] => John Doe [age] => 30 )
error_log()
error_log()
The function logs a message to the error log. This is useful for logging debugging information, errors or warnings.
error_log('调试信息:变量 $name 为空。');
Practical case
Suppose you have a function that counts the number of words in a string. However, this function returns incorrect results. You can use these PHP built-in functions to debug your code:
function word_count($string) { // 分割字符串成单词 $words = explode(' ', $string); // 返回单词数量 return count($words); } // 测试函数 $string = 'This is a test string.'; $result = word_count($string); // 检查结果 if ($result != 5) { error_log('函数 word_count() 返回错误的结果。'); }
By logging debugging information using the error_log()
function, you can easily pinpoint why a function returns incorrect results.
The above is the detailed content of How to debug code using PHP built-in functions?. For more information, please follow other related articles on the PHP Chinese website!