Download the PHP package jasny/typecast without Composer
On this page you can find all versions of the php package jasny/typecast. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download jasny/typecast
More information about jasny/typecast
Files in jasny/typecast
Package typecast
Short Description Type casting with basic logic
License MIT
Homepage http://jasny.github.com/typecast
Informations about the package typecast
Jasny TypeCast
This library does type casting in PHP.
Type casting is natively supported in PHP. This library adds some basic logic to the process, like triggering a warning
when casting a string like "FOO"
to an integer.
In contrary to PHP's internal type casting, casting null
always results in null
.
Installation
The Jasny TypeCast package is available on packagist. Install it using composer:
composer require jasny/typecast
Usage
Alias
You can set aliases in cases where you might need to cast to an interface or abstract class or when you want to cast to a child class.
Errors
By default an E_NOTICE
is triggered if a value can't be casted to desired type. Jasny\TypeCast
follows stricter
rules than PHP for casting values.
Instead of a notice an error of any severity can be triggered. Alternatively any Throwable
like an exception or
error can be thrown.
Variable name in error
You can use the setName()
method to set the property or variable name that is casted. This name will be included in
any error triggered when type casting. This can be useful when determining an issue.
Dependency injection
If your application supports dependency injection through containers, create a new TypeCast
object and add it to the
container as a service.
The value()
method will clone the TypeCast
object. Settings like any aliases or custom handlers will propagate.
Assume that Container
is any PSR-11 compatible container.
Handlers
The Typecast
object uses handlers to cast a value. Each handler can cast a value to a specific type. The following
handlers are defined:
- array (includes typed arrays as
string[]
andDateTime[]
) - boolean
- float
- integer
- number (
int|float
) - mixed
- object (includes casting to a specific class)
- resource
- string
- multiple (e.g.
int|string
andstring|string[]
)
You may overwrite the handlers when creating the TypeCast
object.
Desire
The desire
method will return the handler. This is an alternative approach of using the value
method. If you need to
cast multiple values to the same type, it's recommendable to get the handler once using desire
.
Multiple handler
In cast multiple types are specified, the handler will try to guess the type the value should be cast in. This might
hurt performance. You may use NoTypeGuess
to have the handler give an error if the type can't be determined.