Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typecast function parameters

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.

like image 418
Kao Avatar asked Oct 22 '12 13:10

Kao


2 Answers

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.

like image 182
Tomas Buteler Avatar answered Oct 20 '22 00:10

Tomas Buteler


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

like image 37
raina77ow Avatar answered Oct 20 '22 01:10

raina77ow