coduo/php-to-string
Convert any PHP value to a readable string with a tiny wrapper. Supports strings, ints, floats, arrays, objects, callables, and resources—handy for logging, debugging, and error messages. Simple install and use: new StringConverter($value).
Installation
composer require coduo/php-to-string
No configuration is required—just autoload the package.
First Use Case Convert any PHP value to a string with a single method call:
use Coduo\PHPToString\PHPToString;
$value = PHPToString::toString(new DateTime());
// Output: "2025-12-02T12:00:00+00:00"
$value = PHPToString::toString(['key' => 'value']);
// Output: "Array ( [key] => value )"
Where to Look First
PHPToString (handles all conversions).tests/ for edge cases (e.g., null, objects, resources).CustomRules for extending behavior.Basic Conversion
Replace var_export() or (string) casts with explicit control:
$string = PHPToString::toString($object);
// More reliable than (string)$object for complex types.
Laravel Integration
AppServiceProvider to serialize model data for logs/APIs:
public function boot()
{
Model::macro('toString', function ($attribute = null) {
return PHPToString::toString($attribute ?? $this->toArray());
});
}
$cleanedInput = collect($request->all())
->map(fn ($value) => PHPToString::toString($value));
Debugging/Logging
Replace dd() or Log::debug() with structured strings:
Log::debug('User data', [
'raw' => PHPToString::toString($user),
'sanitized' => PHPToString::toString($user->only(['name', 'email']))
]);
Custom Formatters Extend for domain-specific needs (e.g., pretty-printing collections):
PHPToString::addRule(
Collection::class,
fn (Collection $collection) => $collection->toJson()
);
Resource Handling
RuntimeException. Use get_resource_type() to check first:
if (is_resource($value)) {
return 'Resource of type: ' . get_resource_type($value);
}
Circular References
self-referencing properties) may cause infinite loops. Use PHPToString::toString($obj, 0) to limit depth.Performance
$cache = [];
$string = $cache[$obj->id] ?? ($cache[$obj->id] = PHPToString::toString($obj));
PHPToString::getRules(); // Returns associative array of [type => formatter]
PHPToString::removeRule(DateTime::class);
Custom Rules Register formatters for your classes:
PHPToString::addRule(
MyCustomClass::class,
fn (MyCustomClass $obj) => "Custom: {$obj->id}"
);
Global Configuration Set default options (e.g., max depth) via static properties:
PHPToString::$maxDepth = 2; // Limit recursion depth.
Laravel Facade Create a facade for cleaner syntax:
// app/Providers/AppServiceProvider.php
PHPToString::macro('toString', fn ($value) => PHPToString::toString($value));
Now use:
use App\PHPToString as PTS;
PTS::toString($value);
How can I help you explore Laravel packages today?