Skip to content
Advertisement

How to define how a PHP object will be shown in VSCode when debugging with XDebug?

I have a feature I use when debugging C# applications in Visual Studio, and I’d like to know if it’s possible to do the same in PHP, when debugging with VSCode and XDebug.

When I worked in C# and Visual Studio Debugger, when you add a object to Debugger Watches, it will by default show the objects class name, but if you override ToString method in this class, the debugger will show the value returned by this functions. For instance, if i have a User class:

public class User {
    public string Name { get; set; }
}

When you add a object of this class to watch, it will shown something like : {YourNameSpace.User}, but if you add a ToString method to the class, it will show the method result (User: Name) as the value.

public override string ToString()
{
    return "User: " + Name;
}

Is there a way to do the same in PHP, with XDebug and VSCode?

Advertisement

Answer

Xdebug does not call __toString() for you automatically, but you can set as a watch:

(string) $object

In short: prefix the variable name by (string) .

This will then force PHP to call the __toString method when Xdebug evaluates the watch.

Of course, for that to work, your PHP class needs to define the __toString() method:

<?php
class User {
    private $Name;

    function __construct($Name)
    {
        $this->Name = $Name;
    }

    function __toString()
    {
        return "User: {$this->Name}";
    }
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement