Home
PHP
Tech Tube
MySQL
Linux
CSS&HTML
JavaScript

PHP debug tricks

Sometimes when you work on a messy code with a lot of dependencies and don't have a nice debug tool you may have to dump some output to get the data that you need. Here are some examples: Get the script that was called:
echo $_SERVER["SCRIPT_NAME"] . PHP_EOL;
The following example seems absurd but it's not always the case. Sometimes you may just want to log something in different methods and classes.
class A {
    public function __construct()
    {
        echo __CLASS__."::".__FUNCTION__ . PHP_EOL;
    }
}
Get a class name:
echo get_class($classObject) . PHP_EOL;
Get the file where a class is defined:
$reflector = new \ReflectionClass(get_class($A));
echo $reflector->getFileName() . PHP_EOL;
Limited backtrace:
var_dump(debug_backtrace(DEBUG_BACKTRACE_PROVIDE_OBJECT | DEBUG_BACKTRACE_IGNORE_ARGS, 3)); die;
If microtime() returns float with only zeros after decimal point createFromFormat returns false. So here's one possible workaround:
for ($i=0;$i<9000000;$i++) {
    $now = \DateTime::createFromFormat('U.u', microtime(true));
    while(!$now) {
        $now = \DateTime::createFromFormat('U.u', microtime(true));
    }
    $now->format("Y-m-d H:i:s.u");
}
echo 'DONE!' . PHP_EOL;
The code below proves that even if we catch some custom exception we should be prepared for the default one.
class ApiException extends Exception {}
class RandomException extends Exception {}

function testExceptions(string $exception)
{
	try {
		throw new $exception("Testing: {$exception}");
	} catch(ApiException $e) {
		echo 'Catch 1: ' . $e->getMessage() . PHP_EOL;
	} catch(Exception $e) {
		echo 'Catch 2: ' . $e->getMessage() . PHP_EOL;
	}	
}

testExceptions('ApiException');
testExceptions('RandomException');
testExceptions('Exception');