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 →
CPX: The Composer Package Executor for PHP image

CPX: The Composer Package Executor for PHP

Read article
Laravel AI SDK Adds Human-in-the-Loop Tool Approval image

Laravel AI SDK Adds Human-in-the-Loop Tool Approval

Read article
Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals image

Pest 5 Released With Test Impact Analysis, Agent Verification, and Evals

Read article
Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs image

Queue-SQL: Run Mass Deletes and Updates Across Parallel Queue Jobs

Read article
Blade Formatting in Laravel Pint image

Blade Formatting in Laravel Pint

Read article
Inertia DevTools Is Now on the Chrome Web Store image

Inertia DevTools Is Now on the Chrome Web Store

Read article