• Czas czytania ~1 min
  • 07.06.2023

Strictus jest pakietem, który wprowadza ścisłe wpisywanie zmiennych wbudowanych dla PHP. Biorąc pod uwagę poniższy przykład, PHP nie ma sposobu na wymuszenie silnie wpisanych zmiennych wbudowanych:Używając klasy Strictus, powyższy przykład kodu wygląda teraz następująco:

// 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

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

Powyższy ścisły przykład wyrzuciłby StrictusTypeException if float() odbiera cokolwiek innego niż typ float. Może to być zniechęcające, jeśli jesteś przyzwyczajony do zmiennych dynamicznych, ale myślę, że powinieneś rozważyć, w jaki sposób bardziej rygorystyczne zmienne mogą pomóc.

W chwili pisania tego tekstu ten pakiet obsługuje pojedyncze typy i typy nullable dla String, , Integer, Możesz 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...

dowiedzieć się więcej o tym pakiecie, FloatArrayBooleanObjectuzyskać pełne instrukcje instalacji i wyświetlić kod źródłowy na GitHub.

Comments

No comments yet
Yurij Finiv

Yurij Finiv

Full stack

O

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...

O autorze CrazyBoy49z
WORK EXPERIENCE
Kontakt
Ukraine, Lutsk
+380979856297