3 ms·
AS far as I know, this is because it was and still is common practice to return a result from a function, but return false if something didn't work. Having this
by alex-zierhut 4y ago
AS far as I know, this is because it was and still is common practice to return a result from a function, but return false if something didn't work. Having this type helps return type declaration like: false|ResultObject
In my opinion, using Exceptions or nullable types is a better practice in those cases, but I am not against having more options.
- nicoburns 4y agoYeah it makes a lot of sense just to be able to type existing functions. Seems weir d not to allow true though. I feel like both should be added for completeness.
- matsemann 4y agoKinda make sense, though, as what would that "true" really mean? That the function succeeded? But then the result should be the output.
- cestith 4y agoI don't mind a unit type for failure. I just don't think it should be called "false". Maybe make true and false Boolean and have a unit type for failures called "fail" or "failure".
- djbusby 4y agoPEAR_Error
- simion314 4y agoI think for new code Exceptions are the preferred solution in case your code errors out , much more clear to return just one type of data. So this seems to be just a solution for improving type declaration for older code that that use the pattern to return false in case of error instead of an exception with a much more clear information on what went wrong.
- sfteus 4y agoRight, in the context of PHP it makes sense, as bool would imply you might need to handle a truthy value when in reality the return type of several built-in functions is result|false. Nullable types generally work well, unless you're you have a function that may return nothing, or an error. IE findUser(string $name): ?User wouldn't be able to differentiate between a database error or just not finding a user with that name. Exceptions would work fine here (specifically due to a DB error), but seem a little superfluous for smaller functions. Personally, I've grown to love the tuple return types of Go/Rust, and I'd love to see first-class support for that within PHP. You can emulate it by returning an array and unpacking it / using list(), but it adds a decent amount of boilerplate and you lose aspects of type covariance in always returning an array.