Menu
Coddy logo textTech

__toString & __debugInfo

Part of the Object Oriented Programming section of Coddy's PHP journey — lesson 45 of 91.

The __toString() method lets you define how an object should be represented as a string. This is called automatically when you use an object in a string context, like with echo or string concatenation.

<?php
class User {
    public function __construct(
        private string $name,
        private string $email
    ) {}
    
    public function __toString(): string {
        return $this->name . " (" . $this->email . ")";
    }
}

$user = new User("Alice", "alice@example.com");
echo $user;

Output:

Alice (alice@example.com)

The __debugInfo() method controls what information appears when you use var_dump() on an object. This is useful for hiding sensitive data or showing computed values during debugging:

<?php
class BankAccount {
    public function __construct(
        private string $accountNumber,
        private float $balance,
        private string $pin
    ) {}
    
    public function __debugInfo(): array {
        return [
            'accountNumber' => '****' . substr($this->accountNumber, -4),
            'balance' => $this->balance,
            'pin' => '[HIDDEN]'
        ];
    }
}

$account = new BankAccount("1234567890", 1500.00, "9876");
var_dump($account);

Output:

object(BankAccount)#1 (3) {
  ["accountNumber"]=>
  string(8) "****7890"
  ["balance"]=>
  float(1500)
  ["pin"]=>
  string(8) "[HIDDEN]"
}

Notice how __debugInfo() returns an array of key-value pairs that replace the default property dump. The sensitive PIN is hidden, and the account number is partially masked - perfect for secure debugging.

challenge icon

Challenge

Easy

Let's build a credential management system that demonstrates both __toString() and __debugInfo() magic methods. You'll create a class that displays user-friendly information when printed, while protecting sensitive data during debugging.

You'll organize your code across two files:

  • Credential.php — Create a Credential class that stores login information securely. Use constructor promotion to define private properties for $username (string), $password (string), and $lastLogin (string). Implement two magic methods:
    • __toString() — Returns a user-friendly string: "User: [username] (Last login: [lastLogin])". Notice that the password is never exposed in the string representation.
    • __debugInfo() — Returns an array for var_dump() that shows the username as-is, masks the password by showing only "[PROTECTED]", and displays the last login date normally.
  • main.php — Include the Credential file. You'll receive three inputs: a username, a password, and a last login date. Create a Credential instance with these values. First, echo the credential object directly (this triggers __toString()). Then on a new line, use var_dump() on the object to see the protected debug output.

The __toString() method provides a clean, safe way to display the credential without exposing the password. The __debugInfo() method ensures that even during debugging, sensitive information stays hidden — a crucial practice when working with authentication data.

Cheat sheet

The __toString() method defines how an object is represented as a string when used with echo or string concatenation:

<?php
class User {
    public function __construct(
        private string $name,
        private string $email
    ) {}
    
    public function __toString(): string {
        return $this->name . " (" . $this->email . ")";
    }
}

$user = new User("Alice", "alice@example.com");
echo $user; // Alice (alice@example.com)

The __debugInfo() method controls what information appears when using var_dump() on an object. It returns an array of key-value pairs to display:

<?php
class BankAccount {
    public function __construct(
        private string $accountNumber,
        private float $balance,
        private string $pin
    ) {}
    
    public function __debugInfo(): array {
        return [
            'accountNumber' => '****' . substr($this->accountNumber, -4),
            'balance' => $this->balance,
            'pin' => '[HIDDEN]'
        ];
    }
}

$account = new BankAccount("1234567890", 1500.00, "9876");
var_dump($account);
// Shows masked account number and hidden PIN

These methods are useful for hiding sensitive data or customizing object output for different contexts.

Try it yourself

<?php

require_once 'Credential.php';

// Read inputs
$username = trim(fgets(STDIN));
$password = trim(fgets(STDIN));
$lastLogin = trim(fgets(STDIN));

// TODO: Create a Credential instance with the input values

// TODO: Echo the credential object (triggers __toString())

// TODO: Use var_dump() on the object to see the protected debug output

?>
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming