PHP lacks a mechanism to enforce strongly typed inline variables, as demonstrated by the following example. Strictus is a package that adds strict typing to PHP 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);
Now that the Strictus class has been used, the code example above looks like this:
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
In the strict example above, float() would throw a StrictusTypeException if it received a type other than float. If you’re used to dynamic variables, this might be off-putting, but you should think about how stricter variables could be beneficial.
As of this writing, the following packages are supported: String, Float, Integer, Boolean, Array, Object, and Class; single types and nullable types
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 view the complete installation instructions, find out more about this package, and source code on GitHub.