brick/varexporter
Prettier, safer alternative to PHP var_export(). Exports variables as standalone executable PHP code (no runtime dependency) with short array syntax, cleaner numeric arrays, and support for closures and custom objects beyond __set_state(), ideal for fast OPcache-friendly caching.
Start by installing the package via Composer: composer require brick/varexporter. The main entry point is the VarExporter::export() method, which replaces PHP’s native var_export() and now requires PHP 8.2+. It can serialize and export closures, objects, scalar types, and enums—including stdClass, custom objects, and non-serializable resources (like closures)—without requiring __set_state() or Serializable.
For basic usage:
use Brick\VarExporter\VarExporter;
$exported = VarExporter::export(fn() => 'Hello, World!');
// Returns: 'function () { return "Hello, World!"; }'
$obj = (object) ['name' => 'Alice', 'active' => true];
$exportedObj = VarExporter::export($obj);
// Returns: '(object) ["name" => "Alice", "active" => true]'
// New: Export enums inline
enum Status { case Active; case Inactive; }
$exportedEnum = VarExporter::export(Status::Active, [
VarExporter::INLINE_LITERAL_LIST
]);
// Returns: 'Status::Active'
Check the README for updated examples and API reference.
config/cache), avoiding runtime reflection or eval().VarExporter::export() in artisan commands or dev tools to scaffold code (e.g., generate enum lists, config stubs, or migration templates). Leverage INLINE_LITERAL_LIST for cleaner enum exports.Serializable. Now supports enums in lazy-loaded contexts.php artisan debug:config command). Export enum-based statuses or configurations inline for clarity.Status::Active) using INLINE_LITERAL_LIST for cleaner, more maintainable code generation.php: constraint in composer.json if needed.eval(), exported closures retain references to their scope—ensure no dangerous dependencies (e.g., PDO connections) are captured. Consider cleaning scope or using use()-clauses deliberately.VarExporter::exportWithReferences() cautiously—enable reference tracking only when needed (objects/arrays reused multiple times).preg_replace or trim if file size matters. Use INLINE_LITERAL_LIST for enums to balance readability and compactness.__set_state objects are exported as (object) [...] but won’t reconstruct as the original class. Use Serializer::serialize() (if available) or custom __set_state() implementations if strict type fidelity is required.INLINE_LITERAL_LIST option exports enums as literals (e.g., Status::Active), but this may not work for all enum use cases (e.g., enums with custom backends). Test thoroughly in your context.VarExporter::export()’s optional $options parameter (e.g., VarExporter::export($data, [VarExporter::INLINE_LITERAL_LIST])). Check the source for extensibility points if you need custom handling for enums or other types.How can I help you explore Laravel packages today?