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

masteringlaravel logo
Laravel Code Review

Get expert guidance in a few days with a Laravel code review

Visit Laravel Code Review

The latest

View all →
Agent Run Observability in Laravel AI SDK 0.11 image

Agent Run Observability in Laravel AI SDK 0.11

Read article
Debounced Queued Event Listeners in Laravel image

Debounced Queued Event Listeners in Laravel

Read article
Statamic Mailables Viewer Previews Laravel Emails in the Control Panel image

Statamic Mailables Viewer Previews Laravel Emails in the Control Panel

Read article
Laravel Tackle: Run an AI Coding Agent in Your Laravel App image

Laravel Tackle: Run an AI Coding Agent in Your Laravel App

Read article
Queue::forward(): Reroute Laravel Queues in One Place image

Queue::forward(): Reroute Laravel Queues in One Place

Read article
Laravel Read-Through Filesystem: Lazy Storage Migration image

Laravel Read-Through Filesystem: Lazy Storage Migration

Read article