__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
EasyLet'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 aCredentialclass 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 forvar_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 aCredentialinstance with these values. First, echo the credential object directly (this triggers__toString()). Then on a new line, usevar_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
?>This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesIntroduction to OOPClasses vs ObjectsThe $this KeywordMethodsPropertiesConstructor (__construct)Destructor (__destruct)Recap - Simple Calculator4Inheritance
Basic InheritanceThe parent:: KeywordMethod OverridingThe final KeywordAbstract ClassesRecap - Employee Hierarchy7Encapsulation
Public, Protected, PrivateAccess Modifiers in DepthGetters and SettersInformation HidingConstructor Promotion (8.0)Recap - Student Records System2Namespaces & Autoloading
Introduction to NamespacesThe use KeywordPSR-4 Autoloading StandardComposer AutoloaderRecap - Organized Project5Interfaces & Contracts
Introduction to InterfacesImplementing InterfacesMultiple Interface ImplementInterface vs Abstract ClassType Hinting with InterfacesRecap - Shape Calculator8Magic Methods
Magic Methods Introduction__toString & __debugInfo__get, __set, __isset, __unset__call & __callStatic__clone & Object Cloning__serialize & __unserializeRecap - Custom Collection11Type System & Error Handling
Type DeclarationsNullable TypesUnion & Intersection TypesException ClassesCustom Exception HierarchyTry, Catch, FinallyRecap - Form Validator14Project: Library Management
Project OverviewBook and User Classes3Class Properties
Instance vs Static PropertiesConstants in ClassesStatic Methods & PropertiesPrivate & Protected PropertiesReadonly Properties (PHP 8.1)Recap - Bank Account Manager6Polymorphism
Method Overriding RevisitedPolymorphism via InterfacesType Hinting & Union TypesLate Static BindingRecap - Payment Processor9Traits
Introduction to TraitsUsing Multiple TraitsTrait Conflict ResolutionAbstract Methods in TraitsTraits vs Inheritance12Design Patterns Part 1
Intro to Design PatternsSingleton PatternFactory PatternObserver PatternStrategy Pattern