This PHP code is an example program that demonstrates how to require strict argument types for functions.
<?php // TWO FUNCTION DECLARATIONS // This function can be used with any types, since no argument types are defined. function AddUnknown($qA1, $qA2) { return ($qA1 + $qA2); } // This version specifies int arguments. Non-integers are automatically converted. function AddIntegers(int $iA1, int $iA2) { return ($iA1 + $iA2); } // TWO FUNCTION CALLS // No types are specified. So, they are added as doubles. The string is converted. echo AddUnknown(5.6, "4.1")."<br />"; // This is not valid with strict_types because it requires a conversion. // The arguments automatically converted when strict is not set. // The double and string are truncated during the conversion. echo AddIntegers(5.6, "4.1")."<br />"; ?>
<?php // This causes function to deny arguments that are not of the correct type. declare(strict_types=1); // TWO FUNCTION DECLARATIONS // This function can be used with any types, since no argument types are defined. function AddUnknown($qA1, $qA2) { return ($qA1 + $qA2); } // This version specifies int arguments. Non-integers are automatically converted. function AddIntegers(int $iA1, int $iA2) { return ($iA1 + $iA2); } // TWO FUNCTION CALLS // No types are specified. So, they are added as doubles. The string is converted. echo AddUnknown(5.6, "4.1")."<br />"; // This is not valid with strict_types because it requires a conversion. // The arguments automatically converted when strict is not set. // The double and string are truncated during the conversion. echo AddIntegers(5.6, "4.1")."<br />"; ?>
© 20072024 XoaX.net LLC. All rights reserved.