Home » Php » php – Typecast function parameters

php – Typecast function parameters

Posted by: admin July 12, 2020 Leave a comment

Questions:

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.

How to&Answers:

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…

Answer:

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.

Answer:

For scalars you can use the php is_int() .. is_string() functions to check.

For arrays and objects you can use type hinting in the function call.

There is a rumour that in the next version of php there will also type hinting support for scalars.

Answer:

There will be scalar type-cast-like type-hint in function parameters in php 5.5, but for now, only classes, array & callable only available (as of php 5.4)

Answer:

http://php.net/manual/en/language.oop5.typehinting.php

You cant set such check for INT and STRING.