I would like to check the type of a parameter matches, before I enter a the function.
function ((int) $integer, (string) $string ) { /*...*/ }
As opposed to
function ( $int, $string ) {
$string = (string) $string;
$int = (int) $int;
}
Is there a way to do this? I've also speculated in doing it as object
function ( Integer $int ) { /*...*/ }
By doing this I could send a functionName ( new Integer ( $int ));
but I would love to not have the added syntax.
Starting in PHP 7 you can now use Scalar types (int, float, string, and bool) when type hinting.
function (int $int) { /*...*/ }
function (float $float) { /*...*/ }
function (string $string) { /*...*/ }
function (bool $bool) { /*...*/ }
As of OP's question, PHP only supported type hinting of objects, interfaces and the array
type, but it is now possible to do what the question proposes natively.
You certainly can use so-called type hinting with complex types (arrays, interfaces and objects) - but not with primitives (and, to my mild surprise, with traits as well):
Type hints can not be used with scalar types such as int or string. Traits are not allowed either.
While there's a lot of proposals to add the scalar type hinting to PHP (there's even an informal patch for that), it's not that easy. I'd recommend checking out this article, as it sums up the potential pitfalls of different approaches pretty well.
P.S. BTW, it looks like PHP 5.5 might use that "check-and-cast" type hinting. Not to say I'm surprised...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With