Add Strict Typing to Inline Variables in PHP With Strictus
Published on by Paul Redmond
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); // nullableStrictus::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.