Core PHP

Function with Strict Arguments

This PHP code is an example program that demonstrates how to require strict argument types for functions.

WithoutStrictArgumentTypes.php

<?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 />";

?>
 
 

WithoutStrictArgumentTypes.php Output

 

WithStrictArgumentTypes.php

<?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 />";

?>
 
 

WithStrictArgumentTypes.php Output

 
 

© 2007–2024 XoaX.net LLC. All rights reserved.