PHPackages                             petrknap/optional - 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. petrknap/optional

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

petrknap/optional
=================

Optional (like in Java Platform SE 8 but in PHP)

v3.5.2(4mo ago)075.1k↓37.1%[3 PRs](https://github.com/petrknap/php-optional/pulls)5LGPL-3.0-or-laterPHPPHP &gt;=8.1

Since May 10Pushed 4mo ago1 watchersCompare

[ Source](https://github.com/petrknap/php-optional)[ Packagist](https://packagist.org/packages/petrknap/optional)[ Docs](https://github.com/petrknap/php-optional)[ Fund](https://petrknap.github.io/donate.html)[ RSS](/packages/petrknap-optional/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (5)Versions (34)Used By (5)

Optional (like in Java Platform SE 8 but in PHP)
================================================

[](#optional-like-in-java-platform-se-8-but-in-php)

> A container object which may or may not contain a non-null value. If a value is present, `isPresent()` will return `true` and `get()` will return the value.
>
> Additional methods that depend on the presence or absence of a contained value are provided, such as `orElse()` (return a default value if value not present) and `ifPresent()` (execute a block of code if the value is present).
>
> This is a [value-based](https://docs.oracle.com/javase/8/docs/api/java/lang/doc-files/ValueBased.html) class; use of identity-sensitive operations (including reference equality (==), identity hash code, or synchronization) on instances of Optional may have unpredictable results and should be avoided.
>
> \-- [Optional (Java Platform SE 8)](https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html)

It is an easy way to make sure that everyone has to check if they have (not) received a `null`.

Examples
--------

[](#examples)

```
namespace PetrKnap\Optional;

/** @var Optional $optionalString */
$optionalString = Optional::of('data');
if ($optionalString->isPresent()) {
    echo $optionalString->get();
}

OptionalResource::ofFalsable(tmpfile())->ifPresent(function ($tmpFile): void {
    fwrite($tmpFile, 'data');
    fclose($tmpFile);
}, else: fn () => print('tmpfile() failed'));
```

### Create and use your own typed optional

[](#create-and-use-your-own-typed-optional)

```
namespace PetrKnap\Optional;

/**
 * @extends OptionalObject
 */
class YourOptional extends OptionalObject {
    protected static function getInstanceOf(): string {
        return Some\DataObject::class;
    }
}
TypedOptional::register(YourOptional::class); // optional recommended step

function your_strong_typed_function(YourOptional $input): YourOptional {
    return YourOptional::empty();
}

/**
 * @param Optional $input
 *
 * @return Optional
 */
function your_weak_typed_function(Optional $input): Optional {
    return YourOptional::empty();
}
```

---

Run `composer require petrknap/optional` to install it. You can [support this project via donation](https://petrknap.github.io/donate.html). The project is licensed under [the terms of the `LGPL-3.0-or-later`](./COPYING.LESSER).

###  Health Score

49

—

FairBetter than 95% of packages

Maintenance77

Regular maintenance activity

Popularity30

Limited adoption so far

Community13

Small or concentrated contributor base

Maturity61

Established project with proven stability

 Bus Factor1

Top contributor holds 100% 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 ~21 days

Recently: every ~88 days

Total

30

Last Release

128d ago

Major Versions

v1.9.1 → v2.0.02024-05-24

v2.1.2 → v3.0.02024-05-29

### Community

Maintainers

![](https://www.gravatar.com/avatar/c0e19f2ea17567eb9f536d1e00595b83630dfb8b2df6e7e422e06a9a48e85585?d=identicon)[petrknap](/maintainers/petrknap)

---

Top Contributors

[![petrknap](https://avatars.githubusercontent.com/u/8299754?v=4)](https://github.com/petrknap "petrknap (84 commits)")

---

Tags

datatypeoptionalphpphp-librarytypetypeoptionaldatatype

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP\_CodeSniffer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/petrknap-optional/health.svg)

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

###  Alternatives

[phpoption/phpoption

Option Type for PHP

2.7k541.2M159](/packages/phpoption-phpoption)[jetbrains/phpstorm-stubs

PHP runtime &amp; extensions header files for PhpStorm

1.4k27.7M68](/packages/jetbrains-phpstorm-stubs)[marc-mabe/php-enum

Simple and fast implementation of enumerations with native PHP

49644.8M97](/packages/marc-mabe-php-enum)[symfony/type-info

Extracts PHP types information.

19951.9M114](/packages/symfony-type-info)[consistence/consistence

Consistence - consistent approach and additions to PHP's functionality

1831.1M18](/packages/consistence-consistence)[pinkary-project/type-guard

Type Guard module is part of the Pinkary Project, and allows you to \*\*narrow down the type\*\* of a variable to a more specific type.

198102.4k14](/packages/pinkary-project-type-guard)

PHPackages © 2026

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