PHPackages                             jasny/typecast - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. jasny/typecast

Abandoned → [improved/type](/?search=improved%2Ftype)ArchivedLibrary[Utility &amp; Helpers](/categories/utility)

jasny/typecast
==============

Type casting with basic logic

v2.1.1(9y ago)723.1k↓50%2[3 issues](https://github.com/jasny/typecast/issues)3MITPHPPHP &gt;=5.6.0

Since Aug 30Pushed 5y agoCompare

[ Source](https://github.com/jasny/typecast)[ Packagist](https://packagist.org/packages/jasny/typecast)[ Docs](http://jasny.github.com/typecast)[ RSS](/packages/jasny-typecast/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (2)Dependencies (1)Versions (9)Used By (3)

Jasny TypeCast
==============

[](#jasny-typecast)

[![Build Status](https://camo.githubusercontent.com/2c5ae14d21bb30bcd913bd728ec12f98651ab192ebc3aa44ce051137b637611e/68747470733a2f2f7472617669732d63692e6f72672f6a61736e792f74797065636173742e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/jasny/typecast)[![Code Coverage](https://camo.githubusercontent.com/a7cf0e9d3517234ab482dbf4d831cbd14303f98acae8794f9c887bd23f6add44/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f6a61736e792f74797065636173742f6261646765732f636f7665726167652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/jasny/typecast/?branch=master)[![Scrutinizer Code Quality](https://camo.githubusercontent.com/0bb626858a1397e691d4882199210c9115a82d76978d14f1425d9ff9c87bea16/68747470733a2f2f7363727574696e697a65722d63692e636f6d2f672f6a61736e792f74797065636173742f6261646765732f7175616c6974792d73636f72652e706e673f623d6d6173746572)](https://scrutinizer-ci.com/g/jasny/typecast/?branch=master)[![SensioLabsInsight](https://camo.githubusercontent.com/afe57da8a0e2a4d67d1acec117059a68baaf4d7b95193e4a6ad436cd922d2807/68747470733a2f2f696e73696768742e73656e73696f6c6162732e636f6d2f70726f6a656374732f64353036393166322d346263622d346366372d393935612d3039386132636534373861632f6d696e692e706e67)](https://insight.sensiolabs.com/projects/d50691f2-4bcb-4cf7-995a-098a2ce478ac)

This library does [type casting in PHP](http://php.net/manual/en/language.types.type-juggling.php#language.types.typecasting).

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
------------

[](#installation)

The Jasny TypeCast package is available on [packagist](https://packagist.org/packages/jasny/meta). Install it using composer:

```
composer require jasny/typecast

```

Usage
-----

[](#usage)

```
use Jasny\TypeCast;

$typecast = new TypeCast();

$typecast->to('string')->cast(null); // null

$typecast->to('integer')->cast('987'); // 987
$typecast->to(DateTime::class)->cast('2015-01-01'); // new DateTime('2015-01-01)
$typecast->to(FooBar::class)->cast($data); // FooBar::__set_state($data)

// Unable to cast
$typecast->to('float')->cast('red'); // 'red' + triggers a notice
$typecast->to('int')->cast(new stdClass()); // stdClass object + triggers a notice
```

### Alias

[](#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.

```
$typecast = new TypeCast();
$typecast->alias(FooBarInterface::class, FooBar::class);

$typecast->to(FooBarInterface::class)->cast($data); // FooBar::__set_state($data)
```

### Errors

[](#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.

```
$typecast = new TypeCast();

$typecast->failWith(E_USER_WARNING);
$typecast->failWith(TypeError::class);
$typecast->failWith(UnexpectedValueException::class);
```

#### Variable name in error

[](#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.

```
$foo = 'red';
$typecast->value($foo)->setName('foo')->to('float');
```

### Dependency injection

[](#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.

```
use Jasny\TypeCast;
use Jasny\TypeCastInterface;

$container = new Container([
  TypeCastInterface::class => function() {
    $typecast = new TypeCast();
    $typecast->alias(FooBarInterface::class, FooBar::class);

    return $typecast;
  }
]);

$container->get(TypeCastInterface::class)->value('987')->to('integer');
```

*Assume that `Container` is any [PSR-11 compatible container](https://www.php-fig.org/psr/psr-11/).*

### Handlers

[](#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[]` and `DateTime[]`)*
- boolean
- float
- integer
- number *(`int|float`)*
- mixed
- object *(includes casting to a specific class)*
- resource
- string
- multiple *(e.g. `int|string` and `string|string[]`)*

You may overwrite the handlers when creating the `TypeCast` object.

#### Desire

[](#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`.

```
use Jasny\TypeCast;

$typecast = new TypeCast();
$typecast->desire('integer')->cast('10');

$arrayHandler = $typecast->desire('array');
foreach ($items as &$item) {
  $item = $arrayHandler->cast($item);
}
```

#### Multiple handler

[](#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.

```
use Jasny\TypeCast;

$multipleHandler = new TypeCast\Handlers\MultipleHandler(new TypeCast\NoTypeGuess());
$typecast = new TypeCast(null, ['multiple' => $multipleHandler] + TypeCast::getDefaultHandlers());
```

###  Health Score

33

—

LowBetter than 75% of packages

Maintenance11

Infrequent updates — may be unmaintained

Popularity30

Limited adoption so far

Community14

Small or concentrated contributor base

Maturity63

Established project with proven stability

 Bus Factor1

Top contributor holds 65.7% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~66 days

Recently: every ~54 days

Total

8

Last Release

3448d ago

Major Versions

v1.0.2 → v2.0.02016-05-05

PHP version history (2 changes)v1.0.0PHP &gt;=5.4.0

v2.0.0PHP &gt;=5.6.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/3379a93d51305df325df9045e1a8b205d195e4e8c01312dff53a000ee79002eb?d=identicon)[jasny](/maintainers/jasny)

---

Top Contributors

[![jasny](https://avatars.githubusercontent.com/u/100821?v=4)](https://github.com/jasny "jasny (44 commits)")[![Minstel](https://avatars.githubusercontent.com/u/6154708?v=4)](https://github.com/Minstel "Minstel (23 commits)")

---

Tags

type-casting

### Embed Badge

![Health badge](/badges/jasny-typecast/health.svg)

```
[![Health](https://phpackages.com/badges/jasny-typecast/health.svg)](https://phpackages.com/packages/jasny-typecast)
```

###  Alternatives

[jrfnl/php-cast-to-type

PHP Class to consistently cast variables to a specific type.

13251.5k4](/packages/jrfnl-php-cast-to-type)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
