How to echo a custom object in PHP?

How to echo a custom object in PHP?

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Echoing Custom Objects in PHP: The __toString Solution

You cannot overload the echo statement in PHP, nor can you make it behave differently based on the type of variable it encounters without specific hooks. When you write echo $foo;, the engine simply calls print($foo). If $foo is an object and no special method exists to handle its string representation, PHP attempts to cast the object to a string. In modern PHP versions (5.4+), this results in a fatal error: "Object of class TheClass could not be converted to string." However, if you are running on an older version like 5.2.6, or simply want to control the output gracefully, the standard solution is implementing the __toString() magic method.

By defining __toString() within your class, you intercept the casting process and return a string representation instead of letting PHP default behavior take over. This allows you to write clean code like echo $foo; and have it automatically output $foo->Name and $foo->Number.

Here is how you implement this for your specific use case:

class TheClass {
    public $Name;
    public $Number;

    // This magic method handles the conversion to string
    public function __toString() {
        return "Name: {$this->Name}, Number: {$this->Number}";
    }

    public function MrFunction() {
        // Your existing logic here
    }
}

$foo = new TheClass();
$foo->Name = 'Alice';
$foo->Number = 123;

echo $foo; 
// Output: Name: Alice, Number: 123

When PHP encounters echo $foo, it effectively runs string($foo). The engine looks for __toString(). If found and returns a string, the echo statement prints that result. If __toString() is missing or returns something other than a string, you will encounter runtime errors depending on your PHP version.

Handling Inheritable Classes

One critical detail when implementing __toString involves class inheritance and polymorphism. If you extend TheClass, the child class must also define its own __toString() method if it wants to output different data or formatting than the parent. You cannot rely on the parent's implementation unless it is designed to be generic enough.

Consider a scenario where you have an array of objects:

$objects = [$foo, new TheClass()];
foreach ($objects as $obj) {
    echo "{$obj}\n"; 
}

This loop relies entirely on each object's __toString() method to generate the content for that iteration. If one object lacks this method, the entire application may crash or display unexpected warnings if you are not careful with error reporting settings.

Trade-offs and Best Practices

While __toString solves the immediate problem of echoing an object, there are trade-offs developers should consider.

1. Security Implications:
If your class contains sensitive data (passwords, tokens, or internal IDs), returning that data directly in __toString can be a security risk. Ensure you filter out sensitive properties before returning the string. Never blindly return $this or concatenate raw variables without sanitization.

2. Return Type Constraints:
The method must return a string. If you accidentally return an integer or another object, PHP will cast it again, potentially causing infinite loops or unexpected behavior in strict mode. Always use return (string) '...' to be explicit.

3. Debugging Clarity:
When debugging large arrays or collections, having every object print a verbose string can clutter logs. Consider adding a flag or checking the context, though this is less common in standard PHP logic compared to frameworks like Laravel where you might use dd() or dump().

If you are working within the Laravel ecosystem, you might find similar patterns useful when debugging models or collections. The framework provides tools to dump objects nicely, but understanding __toString remains fundamental for custom classes outside of that context. For more details on how Laravel handles object dumping and debugging, you can refer to their documentation at https://laravelcompany.com.

Conclusion

To summarize, if you need echo $foo to print specific properties like Name and Number, implementing the __toString() magic method is the correct approach. It bridges the gap between object-oriented programming and PHP's string output functions without requiring changes to how you call your methods. Just remember to handle inheritance carefully and ensure you only return safe, formatted strings.

Our network