Home > database >  PHP Xdebug Overrides __Dir__ and __File__ constant
PHP Xdebug Overrides __Dir__ and __File__ constant

Time:11-16

While debugging a PHP script using the "Listen for XDebug" in VS code(PHP Debug by Felix Becker extension), I found that the __DIR__ and __File__ which are supposed to return the directory and the filename of the current running script are being overridden by Xdebug:

__DIR__ contains
"xdebug:"
__FILE__ contains
"xdebug://debug-eval"

However, if I assign the values to local variables, it works as expected.

$dir = __DIR__; // $dir holds the correct path, instead of "xdebug:"

This issue was encountered here Xdebug weird __DIR__ constant.

However the post is old, and is missing resourceful explanation for the unexpected behavior.

Your help is appreciated.

CodePudding user response:

The output you get is not incorrect. __FILE__ is a special constant that gets evaluated at parser time. When the PHP script gets compiled, it would really read something like this:

// test.php
<?php
    "test.php";
?>

even though the script source was:

// test.php
<?php
    __FILE__;
?>

This means that after parsing, there is no such "constant" __FILE__ at all, as it has already been replaced.

This means that if you do in an IDE, through DBGp's eval command eval -- __FILE__ it can not give you the __FILE__ with any filename. Instead, it uses the filename for the current context which is xdebug eval or in later versions, xdebug://debug-eval.

In essence, it's the same as doing this:

php -r 'eval("__FILE__;");'

Which also outputs:

Command line code(1) : eval()'d code

Xdebug looks for this sort of format, and changes it to xdebug://debug-eval so that it can actually debug into eval'ed code.

__FILE__ works as expected in PHP source code, as can be proven with this snippet:

<?php $far = __FILE__; // now evaluate $far in your IDE ?>
  • Related