Laravel Packages

Add Strict Typing to Inline Variables in PHP With Strictus

Published
Add Strict Typing to Inline Variables in PHP With Strictus image

Strictus is a package that brings strict typing to inline variables for PHP. Given the following example, PHP doesn't have a way to enforce strongly-typed inline variables:

// Rule: Active discount of 10% or 25% for orders from $50
$total = 82.50;
$discount = 0.10; // Float
 
if ($total >= 50) {
$discount = '25%'; // Replacing a float value with string value 🤦🏻‍♂️
}
 
$total = $total - ($total * $discount); //💥 Error: A float cannot be multiplied by a string

Using the Strictus class, the above code example now looks like the following:

use Strictus\Strictus;
 
$total = Strictus::float(82.50);
$discount = Strictus::float(0.10);
 
if ($total() >= 50) {
$discount(0.25); // Updates the $discount value
}
 
$total($total() - ($total() * $discount()));
 
echo $total(); // 61.875

The above strict example would throw a StrictusTypeException if float() receives anything other than a float type. This might be off-putting if you are used to dynamic variables, but I think you should consider how having stricter variables might help.

At the time of writing, this package supports single types and nullable types for String, Float, Integer, Boolean, Array, Object, Class

use Strictus\Strictus;
 
Strictus::string($value);
Strictus::string($value, true); // nullable
Strictus::nullableString($value); // nullable shortcut
 
Strictus::int($value);
Strictus::int($value, true); // nullable
 
Strictus::float($value);
Strictus::float($value, true); // nullable
 
// And so on...

You can learn more about this package, get full installation instructions, and view the source code on GitHub.

Paul Redmond photo

Staff writer at Laravel News. Full stack web developer and author.

Sponsored

laravelcloud logo
Laravel Cloud

Easily create and manage your servers and deploy your Laravel applications in seconds.

Visit Laravel Cloud

The latest

View all →
PayZephyr: One Payment API for Stripe, Paystack, and PayPal image

PayZephyr: One Payment API for Stripe, Paystack, and PayPal

Read article
Bifrost Turns One With AI Builds and New Workflows image

Bifrost Turns One With AI Builds and New Workflows

Read article
Preview Blade Templates in macOS Finder with Quick Blade image

Preview Blade Templates in macOS Finder with Quick Blade

Read article
Artisan Debugging Commands in Laravel Telescope 5.24.0 image

Artisan Debugging Commands in Laravel Telescope 5.24.0

Read article
Queue totalSize() and JobInterrupted Event in Laravel 13.31 image

Queue totalSize() and JobInterrupted Event in Laravel 13.31

Read article
Find Unexpected Test Inputs with Fuzz for Pest image

Find Unexpected Test Inputs with Fuzz for Pest

Read article