DEV Community

Discussion on: Result<T, E> type in PHP

Collapse
 
mindplay profile image
Rasmus Schultz

Unfortunately, this pattern does not give you any type-safety in PHP - and therefore no real guarantees or safety, like you would get in Go or Rust.

You can work around that with generic type-annotations using something like PHPStan or another type-checker - but personally, I find the most explicit approach is a simply type union like Result|Error as you can see for example here:

github.com/mindplay-dk/timber/blob...

The explicit return type encourages the caller to use an instanceof type-check, which (in most IDEs and tools like PHPStan) will correctly narrow the local variable type in an if/else block.

This way, you avoid introducing a pseudo-generic abstract "result" type, which becomes a global dependency in your projects.

To really leverage this pattern, use a pair of case-dependent return types in your return type unions - for example, a createInvoice method might return Invoice|InvoiceError, such that you have two independent classes representing a successful invoice or providing details about why invoicing failed.

Bringing features from one language into another can sometimes make sense, but in this case, union types in PHP already work better than a generic result-type - they only really work well in languages that support generics, and in practice, a type union in PHP works much like the generic result-types in other languages anyway.