• Reading time ~ 1 min
  • 07.06.2023

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.

Comments

No comments yet
Yurij Finiv

Yurij Finiv

Full stack

ABOUT

Professional Fullstack Developer with extensive experience in website and desktop application development. Proficient in a wide range of tools and technologies, including Bootstrap, Tailwind, HTML5, CSS3, PUG, JavaScript, Alpine.js, jQuery, PHP, MODX, and Node.js. Skilled in website development using Symfony, MODX, and Laravel. Experience: Contributed to the development and translation of MODX3 i...

About author CrazyBoy49z
WORK EXPERIENCE
Contact
Ukraine, Lutsk
+380979856297